Last active
December 6, 2020 19:28
-
-
Save Rowadz/8609bf59e81d4c5baf1b76b5dd0ad5e9 to your computer and use it in GitHub Desktop.
generic angular http service
This file contains hidden or 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
| import { Injectable } from '@angular/core'; | |
| import { HttpClient } from '@angular/common/http'; | |
| import { Observable } from 'rxjs'; | |
| import { isNull } from 'util'; | |
| interface QueryParams { | |
| [key: string]: string | number; | |
| } | |
| export interface Post { | |
| id: number; | |
| title: string; | |
| body: string; | |
| userId: number; | |
| } | |
| @Injectable({ | |
| providedIn: 'root' | |
| }) | |
| export class NaomitsuService { | |
| private readonly END_POINT: string; // usually get this from enviroment !! | |
| constructor(private http: HttpClient) { | |
| this.END_POINT = 'https://jsonplaceholder.typicode.com'; | |
| } | |
| /** | |
| * | |
| * * the user here can pass the return type | |
| * e.g : this.serviec.getRemove<_TYPE_>(....) | |
| * * if the user dose not provide an id this will just get all | |
| * resources for a specific route | |
| * * this will work on get and delete request with query params filtering | |
| */ | |
| getRemove<returnType>( | |
| id: number | null, | |
| route: string, | |
| qp: QueryParams = {}, | |
| method: 'get' | 'delete' = 'get' | |
| ): Observable<returnType> { | |
| const cfqu = this.correctFormatForQueryUrl(qp); | |
| return this.http[method]( | |
| `${this.END_POINT}/${route}${id ? '/' + id : ''}${cfqu}` | |
| ) as Observable<returnType>; | |
| } | |
| /** | |
| * this method will patch or post to any route | |
| * you choose | |
| */ | |
| postPatch<returnType>( | |
| route: string, | |
| data: any, | |
| id: number = null, | |
| method: 'post' | 'patch' = 'post', | |
| qp: QueryParams = {} | |
| ): Observable<returnType> { | |
| const cfqu = this.correctFormatForQueryUrl(qp); | |
| return this.http[method]( | |
| `${this.END_POINT}/${route}${id ? '/' + id : ''}${cfqu}`, | |
| data | |
| ) as Observable<returnType>; | |
| } | |
| /** | |
| * In the return we will attach the '?' if the user provides a query params | |
| * and if the user provides a null we do not need to map the array to | |
| * anything, we just simply returns ''. | |
| * if there qp dose has some keys an values | |
| * e.g | |
| * const z = {userId: 1, name: 'rowad'} then | |
| * this method will return ["userId=1", "name=rowad"] | |
| */ | |
| private correctFormatForQueryUrl(qp: QueryParams): string { | |
| if (isNull(qp)) { | |
| return ''; | |
| } | |
| const qpAsStr = this.mapQueryParamsToUrl(qp); | |
| return qpAsStr.length === 0 ? '' : `?${qpAsStr.join('&')}`; | |
| } | |
| /** | |
| * e.g : | |
| * const z = {userId: 1, name: 'rowad'} then | |
| * this method will return ["userId=1", "name=rowad"] | |
| */ | |
| private mapQueryParamsToUrl(qp: QueryParams): Array<string> { | |
| return Object.keys(qp).map((key: string) => { | |
| return `${key}=${qp[key]}`; | |
| }); | |
| } | |
| } | |
| // USAGE | |
| // inside a component | |
| @Component({ | |
| selector: 'app-root', | |
| templateUrl: './app.component.html', | |
| styleUrls: ['./app.component.scss'] | |
| }) | |
| export class AppComponent implements OnInit { | |
| constructor(private naomitsuService: NaomitsuService) {} | |
| ngOnInit(): void { | |
| // https://jsonplaceholder.typicode.com/posts?userId=1&name=rowad&polo=1 | |
| // GET posts where userId = 1, name = 'rowad', polo = 1 | |
| this.naomitsuService | |
| .getRemove<Array<Post>>(null, 'posts', { userId: 1, name: 'rowad', polo: 1 }) | |
| .subscribe({ | |
| next: (arrPost: Array<Post>) => { | |
| console.log(arrPost); | |
| }, | |
| error: console.error | |
| }); | |
| // https://jsonplaceholder.typicode.com/posts | |
| // get all posts | |
| this.naomitsuService.getRemove<Array<Post>>(null, 'posts').subscribe({ | |
| next: (arrPost: Array<Post>) => { | |
| console.log(arrPost); | |
| }, | |
| error: console.error | |
| }); | |
| // https://jsonplaceholder.typicode.com/posts/1 | |
| // DELETE post with id of 1 | |
| this.naomitsuService | |
| .getRemove<unknown>(1, 'posts', null, 'delete') | |
| .subscribe({ | |
| next: (p: unknown) => { | |
| console.log(p); | |
| }, | |
| error: console.error | |
| }); | |
| // https://jsonplaceholder.typicode.com/posts?userId=1 | |
| // DELETE where userId = 1 | |
| this.naomitsuService | |
| .getRemove<unknown>(null, 'posts', { userId: 1 }, 'delete') | |
| .subscribe({ | |
| next: (p: unknown) => { | |
| console.log(p); | |
| }, | |
| error: console.error | |
| }); | |
| // https://jsonplaceholder.typicode.com/posts/1 | |
| // GET posts with an id is 1 | |
| this.naomitsuService.getRemove<Post>(1, 'posts').subscribe({ | |
| next: console.log, | |
| error: console.error | |
| }); | |
| // https://jsonplaceholder.typicode.com/posts | |
| // create a post with data | |
| this.naomitsuService | |
| .postPatch<Post>('posts', { title: 'po', body: 'bar', userId: 1 }) | |
| .subscribe({ | |
| next: console.log, | |
| error: console.error | |
| }); | |
| // https://jsonplaceholder.typicode.com/posts?userId=1&test1=yes&test2=no | |
| // update all the posts with a userId = 1, test1 = yes & test2 = no | |
| this.naomitsuService | |
| .postPatch<Post>('posts', { title: 'rowad' }, null, 'patch', { | |
| userId: 1, | |
| test1: 'yes', | |
| test2: 'no' | |
| }) | |
| .subscribe({ | |
| next: console.log, | |
| error: console.error | |
| }); | |
| // https://jsonplaceholder.typicode.com/posts/1 | |
| // PATCH where post has an id of 1 | |
| this.naomitsuService | |
| .postPatch<Post>('posts', { title: 'rowad' }, 1, 'patch') | |
| .subscribe({ | |
| next: console.log, | |
| error: console.error | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment