created the library service with many functions

This commit is contained in:
X4Lo committed 2024-04-01 21:26:28 +00:00
1 parent 876271b6f4
commit 12dbca2ab9
1 file changed
+198
@@ -0,0 +1,198 @@
import { Injectable, OnInit } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable, ReplaySubject, throwError, map, of } from 'rxjs';
import { catchError, switchMap, tap } from 'rxjs/operators';
import { Entry } from '../../shared/models/entry.model';
import { EntryId } from '../../shared/models/entryId.model';
import { EntryRating } from '../../shared/models/entryRating.model';
// import { environment } from '../../../environments/environment';
@Injectable({
providedIn: 'root',
})
export class LibraryService implements OnInit {
// libraryEntries: Entry[] = [];
private libraryEntriesSubject = new ReplaySubject<Entry[]>(1);
private entriesLoaded = false; // Flag to track if the entries have been loaded
constructor(private http: HttpClient) {}
ngOnInit() {}
public getAllEntries(forceFetch: boolean = false): Observable<Entry[]> {
if (this.entriesLoaded && !forceFetch) {
return this.libraryEntriesSubject.asObservable();
} else {
// Note: This now properly chains the observable without directly subscribing here.
return this.fetchAllEntries(forceFetch);
}
}
public refreshEntries(forceFetch: boolean = true): Observable<Entry[]> {
return this.getAllEntries(forceFetch);
}
// private apiUrl = environment.apiBaseUrl;
private backend_apiUrl = ' http://localhost:4000/api/v1';
/**
* Fetches data from the specified endpoint and returns an Observable.
* @param {string} endPoint The URL of the API endpoint to fetch data from.
* @param {Object} params Optional query parameters to append to the request URL.
* @returns {Observable<any>} An Observable that emits the fetched data.
*/
fetchData(
endPoint: string,
params?: { [param: string]: string | number }
): Observable<any> {
// Initialize HttpParams from the provided params object
let httpParams = new HttpParams();
if (params) {
Object.keys(params).forEach((key) => {
httpParams = httpParams.set(key, params[key]);
});
}
return this.http.get<{ results: any[] }>(endPoint, { params: httpParams });
}
private fetchAllEntries(forceFetch: boolean = false): Observable<Entry[]> {
const endPoint = `${this.backend_apiUrl}/entries`;
// If data is already loaded and not force fetching, immediately return the cached observable.
if (this.entriesLoaded && !forceFetch) {
return this.libraryEntriesSubject.asObservable();
} else {
// Data needs to be (re)fetched.
return this.fetchData(endPoint).pipe(
tap((entries) => {
// Cache the latest entries and mark as loaded.
entries.forEach((entry: Entry) => (entry.isInLibrary = true));
this.libraryEntriesSubject.next(entries);
this.entriesLoaded = true;
}),
catchError((error) => {
// Log and rethrow the error for the caller to handle.
console.error('Failed to fetch entries:', error);
this.entriesLoaded = false; // Allow for a retry on subsequent calls.
return throwError(() => new Error('Failed to fetch entries'));
})
);
}
}
/**
* Fetches all library and returns an Observable.
* @returns {Observable<Entry[]>} An Observable that emits the fetched data.
*/
// fetchAllEntries(): Observable<Entry[]> {
// var endPoint = `${this.backend_apiUrl}/entries`;
// return this.fetchData(endPoint).pipe(
// map((response) => {
// return response.map((movie: any) => this.adaptMovieToEntry(movie));
// })
// );
// }
/**
* Fetches library data with page and pagesize and returns an Observable.
* @param {string} endPoint The URL of the API endpoint to fetch data from.
* @param {Object} params Optional query parameters to append to the request URL.
* @returns {Observable<Entry[]>} An Observable that emits the fetched data.
*/
getEntries(page: number, pageSize: number): Observable<Entry[]> {
var endPoint = `${this.backend_apiUrl}/entries`;
return this.fetchData(endPoint, { page: page, pageSize: pageSize }).pipe(
map((response) =>
response.results.map((movie: any) => this.adaptMovieToEntry(movie))
)
);
}
/**
* Retrieves a specific page of entries from the library.
*
* @param page The page number to retrieve.
* @param pageSize Defines the number of entries on each page.
* @returns An Observable emitting the requested page of entries.
*/
getEntriesUsingEndPoint(endPoint: string): Observable<Entry[]> {
return this.fetchData(endPoint).pipe(
map((response) =>
response.results.map((movie: any) => this.adaptMovieToEntry(movie))
)
);
}
addEntry(tmdb_id: string, is_tvserie: boolean): Observable<Entry | null> {
return this.getAllEntries().pipe(
switchMap((entries) => {
const existingEntry = entries.find(
(entry) => entry.entryId.imdb_id === tmdb_id
);
if (existingEntry) {
return of(existingEntry);
} else {
return this.http.post<Entry>(`${this.backend_apiUrl}/entries`, {
tmdb_id: tmdb_id,
is_tvserie: is_tvserie,
});
}
})
);
}
deleteEntry(id: number): Observable<any> {
// Directly attempt to delete the entry without fetching all entries first.
return this.http.delete(`${this.backend_apiUrl}/entries/${id}`);
}
isInLibrary(tmdb_id: string): Observable<Entry | null> {
return this.getAllEntries().pipe(
switchMap((entries) => {
const existingEntry = entries.find((entry) => {
// console.log(entry.entryId.tmdb_id, tmdb_id);
return entry.entryId.tmdb_id == tmdb_id;
});
if (existingEntry) {
return of(existingEntry);
} else {
return of(null);
}
})
);
}
private adaptMovieToEntry(movie: any): Entry {
const entryId = {
tmdb_id: movie.entryId.tmdb_id,
} as EntryId;
const entryRating = {
tmdb_rating: movie.entryRating.tmdb_rating,
} as EntryRating;
var is_tvseries = movie.release_date == null ? true : false;
var release_date = movie.release_date || movie.first_air_date;
return {
entryId: entryId,
entryRating: entryRating,
title: movie.title,
original_title: movie.original_title,
release_date: release_date,
storyline: movie.storyline,
watchlist: movie.storyline,
favorit: false,
hidden: false,
is_tvseries: is_tvseries,
status: movie.status,
poster_path: movie.poster_path,
} as Entry;
}
}