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', providedIn: 'root',
}) })
export class ApiService { export class ApiService {
/**
* Initializes the ApiService with HttpClient and TokenService.
*/
constructor(private http: HttpClient, private tokenService: 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 { private getAuthHeaders(): HttpHeaders {
const token = this.tokenService.getToken(); const token = this.tokenService.getToken();
if (!token) { if (!token) {
@ -19,27 +75,12 @@ export class ApiService {
return new HttpHeaders({ Authorization: `Token ${token}` }); return new HttpHeaders({ Authorization: `Token ${token}` });
} }
get<T>(endpoint: string, auth: boolean = false): Observable<T> { /**
const headers = auth ? { headers: this.getAuthHeaders() } : {}; * Handles HTTP request errors by logging them and returning a throwError observable.
return this.http *
.get<T>(`${environment.baseUrl}${endpoint}`, headers) * @param error The error object received from the HTTP request.
.pipe(catchError(this.handleError)); * @returns An observable that emits the error.
} */
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));
}
private handleError(error: any) { private handleError(error: any) {
console.error('API error:', error); console.error('API error:', error);
return throwError(() => error); return throwError(() => error);

View file

@ -13,13 +13,22 @@ export class AuthService {
passwordFieldType = 'password'; passwordFieldType = 'password';
passwordIcon = './assets/img/close-eye.svg'; passwordIcon = './assets/img/close-eye.svg';
/**
* Initializes the AuthService with ApiService, UserService, and TokenService.
*/
constructor( constructor(
private router: Router,
private apiService: ApiService, private apiService: ApiService,
private userService: UserService, private userService: UserService,
private tokenService: TokenService 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) { async login(body: any, storage: boolean) {
const data = await firstValueFrom( const data = await firstValueFrom(
this.apiService.post<{ token: string }>('/auth/login/', body) 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() { async logout() {
await firstValueFrom(this.apiService.post('/auth/logout/', null, true)); await firstValueFrom(this.apiService.post('/auth/logout/', null, true));
} }
/**
* Registers a new user.
*
* @param body The registration details.
*/
async register(body: any) { async register(body: any) {
await firstValueFrom(this.apiService.post('/auth/register/', body)); await firstValueFrom(this.apiService.post('/auth/register/', body));
} }
/**
* Verifies a user's email address.
*
* @param body The verification data.
*/
async verifyEmail(body: any) { async verifyEmail(body: any) {
await firstValueFrom(this.apiService.post('/auth/verify-email/', body)); 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) { async forgotPassword(body: any) {
await firstValueFrom(this.apiService.post('/auth/forgot-password/', body)); await firstValueFrom(this.apiService.post('/auth/forgot-password/', body));
} }
/**
* Changes the user's password.
*
* @param body The password change details.
*/
async changePassword(body: any) { async changePassword(body: any) {
await firstValueFrom(this.apiService.post('/auth/change-password/', body)); 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) { async checkAuthUserMail(body: any) {
await firstValueFrom(this.apiService.post('/auth/', body)); 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> { checkAuthUser(): Observable<boolean> {
return this.apiService.get<any>('/auth/', true).pipe( return this.apiService.get<any>('/auth/', true).pipe(
map((response) => { map((response) => {
@ -65,12 +107,18 @@ export class AuthService {
); );
} }
/**
* Toggles the visibility of the password input field.
*/
togglePasswordVisibility() { togglePasswordVisibility() {
this.passwordFieldType = this.passwordFieldType =
this.passwordFieldType === 'password' ? 'text' : 'password'; this.passwordFieldType === 'password' ? 'text' : 'password';
this.toggleIcon(); this.toggleIcon();
} }
/**
* Toggles the password visibility icon based on the current state.
*/
toggleIcon() { toggleIcon() {
this.passwordIcon = this.passwordIcon =
this.passwordIcon === './assets/img/close-eye.svg' this.passwordIcon === './assets/img/close-eye.svg'

View file

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

View file

@ -13,6 +13,12 @@ export class MovieService {
} = {}; } = {};
private availableResolutions: string[]; 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( constructor(
private apiService: ApiService, private apiService: ApiService,
private authService: AuthService, private authService: AuthService,

View file

@ -7,14 +7,14 @@ export class ResolutionService {
private readonly AVAILABLE_RESOLUTIONS = ['360p', '720p', '1080p']; 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[] { getAvailableResolutions(): string[] {
return this.AVAILABLE_RESOLUTIONS; 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 } { initMovieIsUploaded(): { [resolution: string]: boolean } {
return Object.fromEntries( 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 { getDefaultResolution(): string {
return this.AVAILABLE_RESOLUTIONS.includes('720p') return this.AVAILABLE_RESOLUTIONS.includes('720p')

View file

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

View file

@ -8,6 +8,9 @@ import { firstValueFrom } from 'rxjs';
export class UserService { export class UserService {
currentUserId: string | null = null; currentUserId: string | null = null;
/**
* Initializes the UserService with ApiService.
*/
constructor(private apiService: 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> { updateWatchedMovies(watchedMovies: any): Promise<any> {
return firstValueFrom( return firstValueFrom(
this.apiService.put( this.apiService.put(