diff --git a/src/app/services/api.service.ts b/src/app/services/api.service.ts index 326d26d..b941895 100644 --- a/src/app/services/api.service.ts +++ b/src/app/services/api.service.ts @@ -10,60 +10,55 @@ import { TokenService } from './token.service'; providedIn: 'root', }) export class ApiService { - private apiUrl = apiConfig.apiUrl; + private readonly apiUrl = apiConfig.apiUrl; constructor(private http: HttpClient, private tokenService: TokenService) {} + request( + method: string, + endpoint: string, + body?: B | null, + params?: Record + ): Observable { + return this.http.request(method, `${this.apiUrl}${endpoint}`, { + body, + params, + headers: this.getHeaders(), + }); + } + + private getHeaders(): HttpHeaders { + const token = this.tokenService.getAuthToken(); + return token + ? new HttpHeaders().set('Authorization', `Token ${token}`) + : new HttpHeaders(); + } + // ------------- TASKS ------------- // getTaskById(taskId: string): Observable { - return this.http.get(`${this.apiUrl}/api/tasks/${taskId}/`); + return this.request('GET', `/api/tasks/${taskId}/`); } getTasksByStatus(status: string): Observable { - return this.http.get(`${this.apiUrl}/api/tasks/`, { - params: { status }, - }); + return this.request('GET', '/api/tasks/', undefined, { status }); } updateTaskStatus(taskId: string, status: string): Observable { - return this.http.put( - `${this.apiUrl}/api/tasks/${taskId}/update_status/`, - { status: status } - ); + return this.request('PUT', `/api/tasks/${taskId}/update_status/`, { + status, + }); } // ------------- USERS ------------- // getUserById(userId: string): Observable { - return this.http.get(`${this.apiUrl}/api/users/${userId}/`); + return this.request('GET', `/api/users/${userId}/`); } getUsersByIds(userIds: string[]): Observable { - return this.http.get(`${this.apiUrl}/api/users/`, { - params: { ids: userIds.join(',') }, + return this.request('GET', '/api/users/', undefined, { + ids: userIds.join(','), }); } - - // ------------- TOKEN ------------- // - - private addAuthHeaders(headers: HttpHeaders): HttpHeaders { - const token = this.tokenService.getAuthToken(); - if (token) { - return headers.set('Authorization', `Token ${token}`); - } - return headers; - } - - post(url: string, body: any): Observable { - let headers = new HttpHeaders(); - headers = this.addAuthHeaders(headers); - return this.http.post(url, body, { headers }); - } - - get(url: string): Observable { - let headers = new HttpHeaders(); - headers = this.addAuthHeaders(headers); - return this.http.get(url, { headers }); - } } diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index 97134b5..440945f 100755 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -7,17 +7,14 @@ import { Observable, of, } from 'rxjs'; -import { apiConfig } from '../environments/config'; import { ApiService } from './api.service'; import { TokenService } from './token.service'; -import { HttpErrorResponse } from '@angular/common/http'; import { ErrorHandlingService } from './error-handling.service'; @Injectable({ providedIn: 'root', }) export class AuthService { - private apiUrl = apiConfig.apiUrl; private currentUserIdSubject = new BehaviorSubject(null); constructor( @@ -28,45 +25,41 @@ export class AuthService { this.currentUserIdSubject.next(this.tokenService.getUserId()); } - async login(body: any, storage: boolean) { + async login(credentials: any, storage: boolean): Promise { try { - const data = await lastValueFrom( - this.apiService.post<{ token: string; userId: string }>( - `${this.apiUrl}/auth/login/`, - body + const { token, userId } = await lastValueFrom( + this.apiService.request<{ token: string; userId: string }>( + 'POST', + `/auth/login/`, + credentials ) ); - this.tokenService.storeAuthToken(data.token, storage); - this.tokenService.storeUserId(data.userId, storage); - this.currentUserIdSubject.next(data.userId); + this.tokenService.storeAuthToken(token, storage); + this.tokenService.storeUserId(userId, storage); + this.currentUserIdSubject.next(userId); } catch (error) { console.error('Login failed:', error); - const errorMessage = this.errorHandlingService.handleHttpError(error); - throw new Error(errorMessage); + throw new Error(this.errorHandlingService.handleHttpError(error)); } } - async logout() { + async logout(): Promise { try { - await lastValueFrom( - this.apiService.post(`${this.apiUrl}/auth/logout/`, {}) - ); + await lastValueFrom(this.apiService.request('POST', `/auth/logout/`)); this.tokenService.deleteAuthToken(); this.tokenService.deleteUserId(); this.currentUserIdSubject.next(null); - window.location.href = '/login'; } catch (error) { console.error('Logout failed:', error); - const errorMessage = this.errorHandlingService.handleHttpError(error); - throw new Error(errorMessage); + throw new Error(this.errorHandlingService.handleHttpError(error)); } } checkAuthUser(): Observable { - return this.apiService.get(`${this.apiUrl}/auth/`).pipe( + return this.apiService.request('GET', `/auth/`).pipe( map(() => true), catchError(() => of(false)) );