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',
})
export class ApiService {
private apiUrl = apiConfig.apiUrl;
private readonly apiUrl = apiConfig.apiUrl;
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 ------------- //
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[]> {
return this.http.get<Task[]>(`${this.apiUrl}/api/tasks/`, {
params: { status },
});
return this.request<Task[]>('GET', '/api/tasks/', undefined, { status });
}
updateTaskStatus(taskId: string, status: string): Observable<Task> {
return this.http.put<Task>(
`${this.apiUrl}/api/tasks/${taskId}/update_status/`,
{ status: status }
);
return this.request<Task>('PUT', `/api/tasks/${taskId}/update_status/`, {
status,
});
}
// ------------- USERS ------------- //
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[]> {
return this.http.get<User[]>(`${this.apiUrl}/api/users/`, {
params: { ids: userIds.join(',') },
return this.request<User[]>('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<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,
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<string | null>(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<void> {
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<void> {
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<boolean> {
return this.apiService.get(`${this.apiUrl}/auth/`).pipe(
return this.apiService.request('GET', `/auth/`).pipe(
map(() => true),
catchError(() => of(false))
);