Created
June 1, 2023 19:12
-
-
Save edvasqueza/d8900ba4edd72c662bf18d45b7f6fcc3 to your computer and use it in GitHub Desktop.
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 { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpClient } from '@angular/common/http'; | |
| import { Observable, of, throwError, timer } from 'rxjs'; | |
| import { mergeMap } from 'rxjs/operators'; | |
| const interceptedUrls = [ | |
| {regex: /\/loans$/, method: 'GET', filename: 'summary.json', returnStatusCode: 200}, | |
| {regex: /\/loans\/\d+$/, method: 'GET', filename: 'detail.json', returnStatusCode: 200} | |
| ] | |
| const jsonResponsesBasePath: string = 'assets/fake-backend-responses/' | |
| @Injectable() | |
| export class FakeBackendInterceptor implements HttpInterceptor { | |
| constructor(private http: HttpClient) {} | |
| intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
| for (const element of interceptedUrls) { | |
| if(request.url.match(element.regex) && request.method === element.method) { | |
| return this.http.get<any>( jsonResponsesBasePath + element.filename).pipe( | |
| mergeMap((data) => { | |
| return buildHttpResponse(data, element.returnStatusCode); | |
| }) | |
| ); | |
| } | |
| } | |
| return next.handle(request); | |
| function buildHttpResponse(body?, status=200, delay=500): Observable<HttpResponse<any>> { | |
| if (status >= 200 && status < 300) { | |
| return timer(delay).pipe( | |
| mergeMap(() => of(new HttpResponse({ status, body }))) | |
| ); | |
| } else { | |
| timer(delay).pipe( | |
| mergeMap(() => throwError(new HttpResponse({ status, body }))) | |
| ); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment