Adding the service and interface code
Here's the code for the service; open the generated file called api.ts and add it:
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { MediaItem, Book, Movie, Music, SearchOptions } from './media';
@Injectable({
providedIn: 'root'
})
export class Api {
private readonly apiUrl = 'http://localhost:3000';
constructor (private http: HttpClient) { }
loadDemoDataIntoGolem(): Observable<string> {
return this.http.get<string>(`${this.apiUrl}/load-data`);
}
getByKey(key: string): Observable<MediaItem> {
return this.http.get<MediaItem>(`${this.apiUrl}/key/${key}`);
}
getAll(): Observable<MediaItem[]> {
return this.http.get<MediaItem[]>(`${this.apiUrl}/query`);
}
getBooks(): Observable<MediaItem[]> {
return this.http.get<Book[]>(`${this.apiUrl}/query?type=books`);
}
getMusic(): Observable<MediaItem[]> {
return this.http.get<Music[]>(`${this.apiUrl}/query?type=music`);
}
getMovies(): Observable<MediaItem[]> {
return this.http.get<Movie[]>(`${this.apiUrl}/query?type=movies`);
}
getSearchOptions(): Observable<SearchOptions> {
return this.http.get<SearchOptions>(`${this.apiUrl}/search-options`);
}
executeQuery(query: string): Observable<any[]> {
return this.http.get<any[]>(`${this.apiUrl}/query?${query}`);
}
save(item: MediaItem): Observable<any> {
// This will POST the complete object to a /media endpoint
return this.http.post<any>(`${this.apiUrl}/save`, item);
}
purge(): Observable<any> {
return this.http.get<any>(`${this.apiUrl}/purge`)
}
}
And here's the interface. Open the generated file called media.ts and add the following:
export interface BookCreate {
type: "book";
title: string;
description: string;
author: string;
genre: string;
rating: number;
owned: boolean;
year: number;
}
export interface Book extends BookCreate {
key: string;
auto_generated: string;
}
export interface MovieCreate {
type: "movie";
title: string;
description: string;
director: string;
genre: string;
rating: number;
watched: boolean;
year: number;
}
export interface Movie extends MovieCreate {
key: string;
auto_generated: string;
}
export interface MusicCreate {
type: "music";
title: string;
description: string;
artist: string;
genre: string;
rating: number;
favorite: boolean;
year: number;
}
export interface Music extends MusicCreate {
key: string;
auto_generated: string;
}
export type MediaItem = Book | Movie | Music;
export interface SearchOptions {
directors: string[];
artists: string[];
authors: string[];
movie_genres: string[];
music_genres: string[];
book_genres: string[];
}
That's all the code! In the next step we'll walk through running everything, and then after that we'll do a walkthrough of what the code does.
Head to Step 7.