Last active
October 30, 2021 04:03
-
-
Save krishna-acondy/da46f5c2680e4c095092b2112ba5a178 to your computer and use it in GitHub Desktop.
Generic Angular HTTP Resource Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class ResourceService<T extends Resource> { | |
constructor( | |
private httpClient: HttpClient, | |
private url: string, | |
private endpoint: string, | |
private serializer: Serializer) {} | |
public create(item: T): Observable<T> { | |
return this.httpClient | |
.post<T>(`${this.url}/${this.endpoint}`, this.serializer.toJson(item)) | |
.pipe(map(data => this.serializer.fromJson(data) as T)); | |
} | |
public update(item: T): Observable<T> { | |
return this.httpClient | |
.put<T>(`${this.url}/${this.endpoint}/${item.id}`, | |
this.serializer.toJson(item)) | |
.pipe(map(data => this.serializer.fromJson(data) as T)); | |
} | |
read(id: number): Observable<T> { | |
return this.httpClient | |
.get(`${this.url}/${this.endpoint}/${id}`) | |
.pipe(map((data: any) => this.serializer.fromJson(data) as T)); | |
} | |
list(queryOptions: QueryOptions): Observable<T[]> { | |
return this.httpClient | |
.get(`${this.url}/${this.endpoint}?${queryOptions.toQueryString()}`) | |
.pipe(map((data: any) => this.convertData(data.items))); | |
} | |
delete(id: number) { | |
return this.httpClient | |
.delete(`${this.url}/${this.endpoint}/${id}`); | |
} | |
private convertData(data: any): T[] { | |
return data.map(item => this.serializer.fromJson(item)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment