Skip to content

Instantly share code, notes, and snippets.

@leonardovff
Last active October 10, 2020 13:17
Show Gist options
  • Save leonardovff/f8199b7dccdebcd1b80731aa36d77592 to your computer and use it in GitHub Desktop.
Save leonardovff/f8199b7dccdebcd1b80731aa36d77592 to your computer and use it in GitHub Desktop.
Base mock interceptor
import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse } from '@angular/common/http';
import { of, throwError } from 'rxjs';
import { BaseMockInterceptor, IMockResolve } from './base-mock.interceptor';
// import { ClientsData } from './client-data';
const AmParticipantsMockData = [{}];
@Injectable()
export class AmParticipantsMock extends BaseMockInterceptor {
// to setting this part
dataMock = AmParticipantsMockData;
localStorageIndex = 'AmParticipantsMockData';
mockResolves: IMockResolve[] = [
{
// get list of dataMock
requestCheck: (request: HttpRequest<any>, data) => {
return request.url.endsWith('/clients') && request.method === 'GET'
},
response: (data, request: HttpRequest<any>) => {
return of(new HttpResponse({ status: 200, body: [...data] }));
}
},
{
// get client by id
requestCheck: (request: HttpRequest<any>, data) => {
return request.url.match(/\/clients\/\d+$/) && request.method === 'GET'
},
response: (data, request: HttpRequest<any>) => {
// find client by id in client array
let urlParts = request.url.split('/');
let id = parseInt(urlParts[urlParts.length - 1]);
let matchedClients = data.filter(client => { return client.id === id; });
let row = matchedClients.length ? matchedClients[0] : null;
return of(new HttpResponse({ status: 200, body: row }));
}
},
{
// edit client by id
requestCheck: (request: HttpRequest<any>, data) => {
return request.url.match(/\/clients\/\d+$/) && request.method === 'PATCH'
},
response: (data, request: HttpRequest<any>) => {
// find client by id in clients array
let urlParts = request.url.split('/');
let id = parseInt(urlParts[urlParts.length - 1]);
let flag = false;
data = data.map(client => {
if (client.id == id) {
flag = true;
return {
id: id,
...request.body
}
}
return client;
});
if (!flag) {
return throwError({ error: { message: 'Not found' } });
}
// save new client
this.updateLocalStorage(data);
return of(new HttpResponse({ status: 200, body: { message: "Success" } }));
}
},
{
// get client by id
requestCheck: (request: HttpRequest<any>, data) => {
return request.url.endsWith('/clients') && request.method === 'POST'
},
response: (data, request: HttpRequest<any>) => {
// get new client object from post body
let newClient = request.body;
data = data.sort((a, b) => b.id - a.id);
newClient.id = data[0].id + 1;
data.push(newClient);
this.updateLocalStorage(data);
// respond 200 OK
return of(new HttpResponse({ status: 200, body: { id: newClient.id } }));
}
},
{
// delete client by id
requestCheck: (request: HttpRequest<any>, data) => {
return request.url.match(/\/clients\/\d+$/) && request.method === 'DELETE'
},
response: (data, request: HttpRequest<any>) => {
// check for fake auth token in header and return client if valid, this security is implemented server side in a real application
// find client by id in clients array
let urlParts = request.url.split('/');
let id = parseInt(urlParts[urlParts.length - 1]);
data = data.filter(u => u.id != id)
this.updateLocalStorage(data);
// respond 200 OK
return of(new HttpResponse({ status: 200 }));
}
}
];
constructor() {
super();
}
}
import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators';
export interface IMockResolve {
requestCheck(request: HttpRequest<any>, data: any): boolean,
response( data: any, request: HttpRequest<any>): Observable<HttpResponse<any>>,
}
@Injectable()
export abstract class BaseMockInterceptor implements HttpInterceptor {
abstract dataMock: any;
abstract localStorageIndex: string;
abstract mockResolves: Array<IMockResolve>;
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let data = this.getDataFromLocalstorageOrMockData(this.localStorageIndex, this.dataMock);
return of(null).pipe(mergeMap(() => {
for (const key in this.mockResolves) {
const mockResolve = this.mockResolves[key];
if(mockResolve.requestCheck(
{...request} as HttpRequest<any>,
{...data},
)){
return mockResolve.response(data, request);
}
}
// pass through any requests not handled above
return next.handle(request);
}))
.pipe(materialize())
.pipe(delay(1000))
.pipe(dematerialize());
}
private getDataFromLocalstorageOrMockData(localStorageIndex: string, dataMock) {
let data: any = JSON.parse(localStorage.getItem(localStorageIndex)) || [];
if (!data.length) {
data = dataMock;
localStorage.setItem(localStorageIndex, JSON.stringify(dataMock));
}
return data;
}
updateLocalStorage(data) {
localStorage.setItem(this.localStorageIndex, JSON.stringify(data));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment