83 lines
2.2 KiB
TypeScript
83 lines
2.2 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
|
import { Observable, catchError, tap, throwError } from 'rxjs';
|
|
import { environment } from '../../environments/environment';
|
|
|
|
export interface SavedPassword {
|
|
_id: string;
|
|
userId: string;
|
|
description: string;
|
|
password: string;
|
|
createdAt: Date;
|
|
}
|
|
|
|
export interface SavePasswordRequest {
|
|
description: string;
|
|
password: string;
|
|
}
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class PasswordService {
|
|
private readonly API_URL = `${environment.apiUrl}/passwords`;
|
|
|
|
constructor(private http: HttpClient) {}
|
|
|
|
private handleError(error: HttpErrorResponse) {
|
|
let errorMessage = 'An unknown error occurred';
|
|
|
|
if (error.error instanceof ErrorEvent) {
|
|
// Client-side error
|
|
errorMessage = error.error.message;
|
|
} else {
|
|
// Backend error
|
|
if (error.error?.message) {
|
|
errorMessage = error.error.message;
|
|
} else if (typeof error.error === 'string') {
|
|
// Try to parse HTML error message
|
|
const match = error.error.match(/<pre>([^<]+)<\/pre>/);
|
|
if (match) {
|
|
errorMessage = match[1].split('<br>')[0];
|
|
} else {
|
|
errorMessage = error.error;
|
|
}
|
|
} else {
|
|
errorMessage = `Server error: ${error.status}`;
|
|
}
|
|
}
|
|
|
|
console.error('Error details:', {
|
|
message: errorMessage,
|
|
status: error.status,
|
|
error: error.error
|
|
});
|
|
|
|
return throwError(() => ({ message: errorMessage, originalError: error }));
|
|
}
|
|
|
|
getPasswords(): Observable<SavedPassword[]> {
|
|
return this.http.get<SavedPassword[]>(this.API_URL).pipe(
|
|
catchError(this.handleError)
|
|
);
|
|
}
|
|
|
|
savePassword(data: SavePasswordRequest): Observable<SavedPassword> {
|
|
return this.http.post<SavedPassword>(this.API_URL, data).pipe(
|
|
catchError(this.handleError)
|
|
);
|
|
}
|
|
|
|
deletePassword(id: string): Observable<void> {
|
|
return this.http.delete<void>(`${this.API_URL}/${id}`).pipe(
|
|
catchError(this.handleError)
|
|
);
|
|
}
|
|
|
|
updatePassword(id: string, data: SavePasswordRequest): Observable<SavedPassword> {
|
|
return this.http.put<SavedPassword>(`${this.API_URL}/${id}`, data).pipe(
|
|
catchError(this.handleError)
|
|
);
|
|
}
|
|
}
|