Skip to content

Instantly share code, notes, and snippets.

@coderkan
Created May 11, 2020 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderkan/c521160653d58024805b0cdaff80b0e2 to your computer and use it in GitHub Desktop.
Save coderkan/c521160653d58024805b0cdaff80b0e2 to your computer and use it in GitHub Desktop.
@Injectable()
export class FakeBackendHttpInterceptor implements HttpInterceptor {
// default employes json path
private _employeeJsonPath = "assets/employes.json";
constructor(private http: HttpClient) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return this.handleRequests(req, next);
}
/**
* Handle request's and support with mock data.
* @param req
* @param next
*/
handleRequests(req: HttpRequest<any>, next: HttpHandler): any {
const { url, method } = req;
if (url.endsWith("/employes") && method === "GET") {
req = req.clone({
url: this._employeeJsonPath,
});
return next.handle(req).pipe(delay(500));
}
if (url.endsWith("/employes") && method === "POST") {
const { body } = req.clone();
// assign a new uuid to new employee
body.id = uuidv4();
return of(new HttpResponse({ status: 200, body })).pipe(delay(500));
}
if (url.match(/\/employes\/.*/) && method === "DELETE") {
const empId = this.getEmployeeId(url);
return of(new HttpResponse({ status: 200, body: empId })).pipe(
delay(500)
);
}
// if there is not any matches return default request.
return next.handle(req);
}
/**
* Get Employee unique uuid from url.
* @param url
*/
getEmployeeId(url: any) {
const urlValues = url.split("/");
return urlValues[urlValues.length - 1];
}
}
/**
* Mock backend provider definition for app.module.ts provider.
*/
export let fakeBackendProvider = {
provide: HTTP_INTERCEPTORS,
useClass: FakeBackendHttpInterceptor,
multi: true,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment