refactor: optimized functions in ApiService and AuthService

This commit is contained in:
Chneemann 2025-03-25 08:25:24 +01:00
parent 04c149ea41
commit 47c7aacbfb
2 changed files with 43 additions and 55 deletions

View file

@ -10,60 +10,55 @@ import { TokenService } from './token.service';
providedIn: 'root', providedIn: 'root',
}) })
export class ApiService { export class ApiService {
private apiUrl = apiConfig.apiUrl; private readonly apiUrl = apiConfig.apiUrl;
constructor(private http: HttpClient, private tokenService: TokenService) {} constructor(private http: HttpClient, private tokenService: TokenService) {}
request<T, B = unknown>(
method: string,
endpoint: string,
body?: B | null,
params?: Record<string, string | number>
): Observable<T> {
return this.http.request<T>(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 ------------- // // ------------- TASKS ------------- //
getTaskById(taskId: string): Observable<Task> { getTaskById(taskId: string): Observable<Task> {
return this.http.get<Task>(`${this.apiUrl}/api/tasks/${taskId}/`); return this.request<Task>('GET', `/api/tasks/${taskId}/`);
} }
getTasksByStatus(status: string): Observable<Task[]> { getTasksByStatus(status: string): Observable<Task[]> {
return this.http.get<Task[]>(`${this.apiUrl}/api/tasks/`, { return this.request<Task[]>('GET', '/api/tasks/', undefined, { status });
params: { status },
});
} }
updateTaskStatus(taskId: string, status: string): Observable<Task> { updateTaskStatus(taskId: string, status: string): Observable<Task> {
return this.http.put<Task>( return this.request<Task>('PUT', `/api/tasks/${taskId}/update_status/`, {
`${this.apiUrl}/api/tasks/${taskId}/update_status/`, status,
{ status: status } });
);
} }
// ------------- USERS ------------- // // ------------- USERS ------------- //
getUserById(userId: string): Observable<User> { getUserById(userId: string): Observable<User> {
return this.http.get<User>(`${this.apiUrl}/api/users/${userId}/`); return this.request<User>('GET', `/api/users/${userId}/`);
} }
getUsersByIds(userIds: string[]): Observable<User[]> { getUsersByIds(userIds: string[]): Observable<User[]> {
return this.http.get<User[]>(`${this.apiUrl}/api/users/`, { return this.request<User[]>('GET', '/api/users/', undefined, {
params: { ids: userIds.join(',') }, 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<T>(url: string, body: any): Observable<T> {
let headers = new HttpHeaders();
headers = this.addAuthHeaders(headers);
return this.http.post<T>(url, body, { headers });
}
get<T>(url: string): Observable<T> {
let headers = new HttpHeaders();
headers = this.addAuthHeaders(headers);
return this.http.get<T>(url, { headers });
}
} }

View file

@ -7,17 +7,14 @@ import {
Observable, Observable,
of, of,
} from 'rxjs'; } from 'rxjs';
import { apiConfig } from '../environments/config';
import { ApiService } from './api.service'; import { ApiService } from './api.service';
import { TokenService } from './token.service'; import { TokenService } from './token.service';
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandlingService } from './error-handling.service'; import { ErrorHandlingService } from './error-handling.service';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class AuthService { export class AuthService {
private apiUrl = apiConfig.apiUrl;
private currentUserIdSubject = new BehaviorSubject<string | null>(null); private currentUserIdSubject = new BehaviorSubject<string | null>(null);
constructor( constructor(
@ -28,45 +25,41 @@ export class AuthService {
this.currentUserIdSubject.next(this.tokenService.getUserId()); this.currentUserIdSubject.next(this.tokenService.getUserId());
} }
async login(body: any, storage: boolean) { async login(credentials: any, storage: boolean): Promise<void> {
try { try {
const data = await lastValueFrom( const { token, userId } = await lastValueFrom(
this.apiService.post<{ token: string; userId: string }>( this.apiService.request<{ token: string; userId: string }>(
`${this.apiUrl}/auth/login/`, 'POST',
body `/auth/login/`,
credentials
) )
); );
this.tokenService.storeAuthToken(data.token, storage); this.tokenService.storeAuthToken(token, storage);
this.tokenService.storeUserId(data.userId, storage); this.tokenService.storeUserId(userId, storage);
this.currentUserIdSubject.next(data.userId); this.currentUserIdSubject.next(userId);
} catch (error) { } catch (error) {
console.error('Login failed:', error); console.error('Login failed:', error);
const errorMessage = this.errorHandlingService.handleHttpError(error); throw new Error(this.errorHandlingService.handleHttpError(error));
throw new Error(errorMessage);
} }
} }
async logout() { async logout(): Promise<void> {
try { try {
await lastValueFrom( await lastValueFrom(this.apiService.request('POST', `/auth/logout/`));
this.apiService.post(`${this.apiUrl}/auth/logout/`, {})
);
this.tokenService.deleteAuthToken(); this.tokenService.deleteAuthToken();
this.tokenService.deleteUserId(); this.tokenService.deleteUserId();
this.currentUserIdSubject.next(null); this.currentUserIdSubject.next(null);
window.location.href = '/login'; window.location.href = '/login';
} catch (error) { } catch (error) {
console.error('Logout failed:', error); console.error('Logout failed:', error);
const errorMessage = this.errorHandlingService.handleHttpError(error); throw new Error(this.errorHandlingService.handleHttpError(error));
throw new Error(errorMessage);
} }
} }
checkAuthUser(): Observable<boolean> { checkAuthUser(): Observable<boolean> {
return this.apiService.get(`${this.apiUrl}/auth/`).pipe( return this.apiService.request('GET', `/auth/`).pipe(
map(() => true), map(() => true),
catchError(() => of(false)) catchError(() => of(false))
); );