Files
Showy/frontend/src/app/core/services/library.service.ts
T

190 lines
6.3 KiB
TypeScript

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
private backend_apiUrl = ' http://localhost:4000/api/v1';
constructor(private http: HttpClient) {}
ngOnInit() {
this.fetchAllEntries(true);
}
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;
/**
* 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 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.mapMovieToEntry(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.mapMovieToEntry(movie))
// )
// );
// }
addEntry(tmdb_id: string, is_tvserie: boolean): Observable<Entry | null> {
return this.getAllEntries().pipe(
switchMap((entries) => {
const existingEntry = entries.find((entry) => {
if (entry.entryId?.tmdb_id) entry.entryId.tmdb_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) => {
if (entries.length == 0) return of(null);
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 mapMovieToEntry(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;
}
}