|
| 1 | +import type { HttpErrorResponse } from '@angular/common/http' |
1 | 2 | import { HttpClient } from '@angular/common/http'
|
2 | 3 | import { inject, Injectable } from '@angular/core'
|
3 | 4 | import type { Observable } from 'rxjs'
|
4 |
| -import { distinctUntilChanged, ReplaySubject, switchMap, take, tap } from 'rxjs' |
5 |
| -import type { CurrentUser, SetDefaultOrganizationResponse } from '@seed/api/user' |
| 5 | +import { catchError, distinctUntilChanged, ReplaySubject, switchMap, take, tap, throwError } from 'rxjs' |
| 6 | +import type { |
| 7 | + CurrentUser, |
| 8 | + GenerateApiKeyResponse, |
| 9 | + PasswordUpdateRequest, |
| 10 | + PasswordUpdateResponse, |
| 11 | + SetDefaultOrganizationResponse, |
| 12 | + UserUpdateRequest, |
| 13 | +} from '@seed/api/user' |
6 | 14 |
|
7 | 15 | @Injectable({ providedIn: 'root' })
|
8 | 16 | export class UserService {
|
@@ -42,4 +50,53 @@ export class UserService {
|
42 | 50 | }),
|
43 | 51 | )
|
44 | 52 | }
|
| 53 | + |
| 54 | + /** |
| 55 | + * Update user |
| 56 | + */ |
| 57 | + updateUser(userId: number, params: UserUpdateRequest): Observable<CurrentUser> { |
| 58 | + return this._httpClient.put<CurrentUser>(`api/v3/users/${userId}/`, params).pipe( |
| 59 | + tap((user) => { |
| 60 | + this._currentUser.next(user) |
| 61 | + }), |
| 62 | + catchError((error: HttpErrorResponse) => { |
| 63 | + console.error('Error occurred while updating user:', error.error) |
| 64 | + return this._currentUser |
| 65 | + }), |
| 66 | + ) |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * Update user |
| 71 | + */ |
| 72 | + updatePassword(params: PasswordUpdateRequest): Observable<PasswordUpdateResponse> { |
| 73 | + return this.currentUser$.pipe( |
| 74 | + take(1), |
| 75 | + switchMap(({ id: userId }) => { |
| 76 | + return this._httpClient.put<PasswordUpdateResponse>(`api/v3/users/${userId}/set_password/`, params) |
| 77 | + }), |
| 78 | + tap(() => { |
| 79 | + this.getCurrentUser().subscribe() |
| 80 | + }), |
| 81 | + catchError((error: HttpErrorResponse) => { |
| 82 | + return throwError(() => error) |
| 83 | + }), |
| 84 | + ) |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * Generate API Key |
| 89 | + */ |
| 90 | + generateApiKey(): Observable<GenerateApiKeyResponse> { |
| 91 | + return this.currentUser$.pipe( |
| 92 | + take(1), |
| 93 | + switchMap(({ id: userId }) => { |
| 94 | + return this._httpClient.post<GenerateApiKeyResponse>(`api/v3/users/${userId}/generate_api_key/`, {}) |
| 95 | + }), |
| 96 | + tap(() => { |
| 97 | + // Refresh user info after changing the API key |
| 98 | + this.getCurrentUser().subscribe() |
| 99 | + }), |
| 100 | + ) |
| 101 | + } |
45 | 102 | }
|
0 commit comments