docs: add comments to functions in the services

This commit is contained in:
Chneemann 2025-04-27 07:10:14 +02:00
parent 189be57023
commit 3f135c9a1b
7 changed files with 146 additions and 25 deletions

View file

@ -9,8 +9,64 @@ import { catchError } from 'rxjs/operators';
providedIn: 'root',
})
export class ApiService {
/**
* Initializes the ApiService with HttpClient and TokenService.
*/
constructor(private http: HttpClient, private tokenService: TokenService) {}
/**
* Sends a GET request to the specified endpoint.
*
* @template T The expected type of the response.
* @param endpoint The API endpoint to send the request to.
* @param auth Whether to include authentication headers. Defaults to false.
* @returns An Observable of type T.
*/
get<T>(endpoint: string, auth: boolean = false): Observable<T> {
const headers = auth ? { headers: this.getAuthHeaders() } : {};
return this.http
.get<T>(`${environment.baseUrl}${endpoint}`, headers)
.pipe(catchError(this.handleError));
}
/**
* Sends a POST request to the specified endpoint with a request body.
*
* @template T The expected type of the response.
* @param endpoint The API endpoint to send the request to.
* @param body The request payload to send.
* @param auth Whether to include authentication headers. Defaults to false.
* @returns An Observable of type T.
*/
post<T>(endpoint: string, body: any, auth: boolean = false): Observable<T> {
const headers = auth ? { headers: this.getAuthHeaders() } : {};
return this.http
.post<T>(`${environment.baseUrl}${endpoint}`, body, headers)
.pipe(catchError(this.handleError));
}
/**
* Sends a PUT request to the specified endpoint with a request body.
*
* @template T The expected type of the response.
* @param endpoint The API endpoint to send the request to.
* @param body The request payload to update.
* @param auth Whether to include authentication headers. Defaults to false.
* @returns An Observable of type T.
*/
put<T>(endpoint: string, body: any, auth: boolean = false): Observable<T> {
const headers = auth ? { headers: this.getAuthHeaders() } : {};
return this.http
.put<T>(`${environment.baseUrl}${endpoint}`, body, headers)
.pipe(catchError(this.handleError));
}
/**
* Generates HTTP headers containing the Authorization token.
* If no token is found, the session is cleared.
*
* @returns A set of HTTP headers including the Authorization token.
*/
private getAuthHeaders(): HttpHeaders {
const token = this.tokenService.getToken();
if (!token) {
@ -19,27 +75,12 @@ export class ApiService {
return new HttpHeaders({ Authorization: `Token ${token}` });
}
get<T>(endpoint: string, auth: boolean = false): Observable<T> {
const headers = auth ? { headers: this.getAuthHeaders() } : {};
return this.http
.get<T>(`${environment.baseUrl}${endpoint}`, headers)
.pipe(catchError(this.handleError));
}
post<T>(endpoint: string, body: any, auth: boolean = false): Observable<T> {
const headers = auth ? { headers: this.getAuthHeaders() } : {};
return this.http
.post<T>(`${environment.baseUrl}${endpoint}`, body, headers)
.pipe(catchError(this.handleError));
}
put<T>(endpoint: string, body: any, auth: boolean = false): Observable<T> {
const headers = auth ? { headers: this.getAuthHeaders() } : {};
return this.http
.put<T>(`${environment.baseUrl}${endpoint}`, body, headers)
.pipe(catchError(this.handleError));
}
/**
* Handles HTTP request errors by logging them and returning a throwError observable.
*
* @param error The error object received from the HTTP request.
* @returns An observable that emits the error.
*/
private handleError(error: any) {
console.error('API error:', error);
return throwError(() => error);

View file

@ -13,13 +13,22 @@ export class AuthService {
passwordFieldType = 'password';
passwordIcon = './assets/img/close-eye.svg';
/**
* Initializes the AuthService with ApiService, UserService, and TokenService.
*/
constructor(
private router: Router,
private apiService: ApiService,
private userService: UserService,
private tokenService: TokenService
) {}
/**
* Attempts to log in the user with the provided credentials.
*
* @param body The login credentials.
* @param storage Whether to persist the token in local storage.
* @throws Error if no token is received upon successful login.
*/
async login(body: any, storage: boolean) {
const data = await firstValueFrom(
this.apiService.post<{ token: string }>('/auth/login/', body)
@ -31,30 +40,63 @@ export class AuthService {
}
}
/**
* Logs out the user by calling the API endpoint.
*/
async logout() {
await firstValueFrom(this.apiService.post('/auth/logout/', null, true));
}
/**
* Registers a new user.
*
* @param body The registration details.
*/
async register(body: any) {
await firstValueFrom(this.apiService.post('/auth/register/', body));
}
/**
* Verifies a user's email address.
*
* @param body The verification data.
*/
async verifyEmail(body: any) {
await firstValueFrom(this.apiService.post('/auth/verify-email/', body));
}
/**
* Initiates a forgot password request.
*
* @param body The email address or related information.
*/
async forgotPassword(body: any) {
await firstValueFrom(this.apiService.post('/auth/forgot-password/', body));
}
/**
* Changes the user's password.
*
* @param body The password change details.
*/
async changePassword(body: any) {
await firstValueFrom(this.apiService.post('/auth/change-password/', body));
}
/**
* Checks if a user's email is associated with an authenticated account.
*
* @param body The email to verify.
*/
async checkAuthUserMail(body: any) {
await firstValueFrom(this.apiService.post('/auth/', body));
}
/**
* Verifies if the current user is authenticated.
*
* @returns An Observable emitting true if authenticated, false otherwise.
*/
checkAuthUser(): Observable<boolean> {
return this.apiService.get<any>('/auth/', true).pipe(
map((response) => {
@ -65,12 +107,18 @@ export class AuthService {
);
}
/**
* Toggles the visibility of the password input field.
*/
togglePasswordVisibility() {
this.passwordFieldType =
this.passwordFieldType === 'password' ? 'text' : 'password';
this.toggleIcon();
}
/**
* Toggles the password visibility icon based on the current state.
*/
toggleIcon() {
this.passwordIcon =
this.passwordIcon === './assets/img/close-eye.svg'

View file

@ -8,18 +8,32 @@ import { HttpErrorResponse } from '@angular/common/http';
export class ErrorService {
private errorSubject = new BehaviorSubject<string>('');
errorText$ = this.errorSubject.asObservable();
displayError = false;
/**
* Sets a new error message and enables error display.
*
* @param message The error message to display.
*/
errorMsg(message: string) {
this.errorSubject.next(message);
this.displayError = true;
}
/**
* Clears the current error message and hides the error display.
*/
clearError() {
this.errorSubject.next('');
this.displayError = false;
}
/**
* Handles an unknown or HTTP error, setting an appropriate error message.
*
* @param error The error object to process.
*/
handleError(error: unknown) {
if (error instanceof HttpErrorResponse) {
const errorMessage = error.error.error || 'An unknown error occurred';

View file

@ -13,6 +13,12 @@ export class MovieService {
} = {};
private availableResolutions: string[];
/**
* Initializes the MovieService with ApiService, AuthService, and ResolutionService
*
* It fetches the available resolutions from the ResolutionService and stores
* them in the availableResolutions field.
*/
constructor(
private apiService: ApiService,
private authService: AuthService,

View file

@ -7,14 +7,14 @@ export class ResolutionService {
private readonly AVAILABLE_RESOLUTIONS = ['360p', '720p', '1080p'];
/**
* Gibt die zentral definierten verfügbaren Auflösungen zurück
* Returns the centrally defined available resolutions
*/
getAvailableResolutions(): string[] {
return this.AVAILABLE_RESOLUTIONS;
}
/**
* Initialisiert ein Objekt, das alle Auflösungen auf `false` setzt
* Initializes an object that sets all resolutions to `false`
*/
initMovieIsUploaded(): { [resolution: string]: boolean } {
return Object.fromEntries(
@ -23,7 +23,7 @@ export class ResolutionService {
}
/**
* Gibt eine Standardauflösung zurück (z.B. '720p'), oder die erste verfügbare
* Returns a default resolution (e.g. '720p'), or the first available resolution.
*/
getDefaultResolution(): string {
return this.AVAILABLE_RESOLUTIONS.includes('720p')

View file

@ -7,6 +7,9 @@ import { Router } from '@angular/router';
export class TokenService {
private readonly TOKEN_KEY = 'authToken';
/**
* Initializes the TokenService with the Router.
*/
constructor(private router: Router) {}
/**

View file

@ -8,6 +8,9 @@ import { firstValueFrom } from 'rxjs';
export class UserService {
currentUserId: string | null = null;
/**
* Initializes the UserService with ApiService.
*/
constructor(private apiService: ApiService) {}
/**
@ -39,6 +42,12 @@ export class UserService {
);
}
/**
* Update the list of watched movies for the current user
*
* @param watchedMovies a list of movie IDs watched by the current user
* @returns a promise resolved when the update is successful
*/
updateWatchedMovies(watchedMovies: any): Promise<any> {
return firstValueFrom(
this.apiService.put(