Skip to content

Instantly share code, notes, and snippets.

@max-lt
Created November 16, 2022 09:30
Show Gist options
  • Save max-lt/e2409c95a9f3614c5887b4d2017c8372 to your computer and use it in GitHub Desktop.
Save max-lt/e2409c95a9f3614c5887b4d2017c8372 to your computer and use it in GitHub Desktop.
import { HttpClient } from '@angular/common/http';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { first, Observable } from 'rxjs';
export abstract class CRUDService<T, C, U extends { id: string }> implements Resolve<T> {
constructor(protected http: HttpClient, protected base: string) {
console.log(`Instantiating ${this.base.slice(0, -1)} service`);
}
public findAll(): Observable<T[]> {
return this.http.get<T[]>('/api/v1/' + this.base);
}
public findById(id: string): Observable<T> {
return this.http.get<T>('/api/v1/' + this.base + '/' + id);
}
public create(params: C): Observable<T> {
return this.http.post<T>('/api/v1/' + this.base, params);
}
public update({ id, ...params }: U): Observable<T> {
return this.http.put<T>('/api/v1/' + this.base + '/' + id, params);
}
public delete(id: string): Observable<number> {
return this.http.delete<number>('/api/v1/' + this.base + '/' + id);
}
public resolve(route: ActivatedRouteSnapshot): Observable<T> {
const id = route.paramMap.get('id');
console.log(`Resolving ${this.base.slice(0, -1)} ${id}`);
if (!id) {
throw new Error(`Missing param "id" to resolve ${this.base.slice(0, -1)}`);
}
return this.findById(id).pipe(first());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment