Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
- import { Injectable } from '@angular/core';
- import { Observable, of, throwError } from 'rxjs';
- import { delay, dematerialize, materialize, mergeMap } from 'rxjs/operators';
- import { environment } from '../../../environments/environment';
- // Based on http://jasonwatmore.com/post/2018/06/22/angular-6-mock-backend-example-for-backendless-development
- @Injectable({
- providedIn: 'root'
- })
- export class FakeBackendApiInterceptor implements HttpInterceptor {
- constructor() { }
- intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
- // array in local storage for registered users
- let users: any[] = JSON.parse(localStorage.getItem('users')) || [];
- // array in local storage for registered events
- let allEvents: any[] = JSON.parse(localStorage.getItem('events')) || {};
- let events: any[] = [];
- // add a dummy user with some dummy events
- users[0] = {
- id: 1,
- username: 'dummy',
- password: 'dummy'
- };
- localStorage.setItem('users', JSON.stringify(users));
- allEvents['dummy'] = (allEvents && allEvents['dummy'] ? allEvents['dummy'] : []);
- allEvents['dummy'][0] = {
- id: 1,
- description: 'Some event in the future',
- date: new Date(2100, 12, 31),
- };
- allEvents['dummy'][1] = {
- id: 2,
- description: 'Some event in the past',
- date: new Date(1900, 12, 31),
- };
- localStorage.setItem('events', JSON.stringify(allEvents));
- // get authenticated user from token (if available)
- let username: string = ('' + request.headers.get('Authorization')).replace('Bearer ', '');
- let user: any = null;
- let filteredUsers = users.filter(user => { return user.username === username; });
- if (filteredUsers && filteredUsers.length) {
- user = filteredUsers[0];
- events = (allEvents && allEvents[username] ? allEvents[username] : []);
- }
- // wrap in delayed observable to simulate server api call
- return of(null).pipe(mergeMap(() => {
- // get current user
- if (request.url.includes(`${environment.API_BASE_URL}${environment.API_GetAuthenticatedUser}`) && request.method === 'GET') {
- // if there is a logged in user return 200 OK with user details and fake jwt token
- if (user) {
- let body = {
- ...user // Copy user details
- };
- return of(new HttpResponse({ status: 200, body: body }));
- } else {
- // return 401 not authorised if token is null or invalid
- return throwError({ error: { message: 'Unauthorised' } });
- }
- }
- // register user
- if (request.url.includes(`${environment.API_BASE_URL}${environment.API_Register}`) && request.method === 'PUT') {
- // get new user object from post body
- let newUser = request.body;
- // validation
- if (!newUser.username) {
- return throwError({ error: { message: 'Username cannot be empty' } });
- }
- let duplicateUser = users.filter(user => { return user.username === newUser.username; }).length;
- if (duplicateUser) {
- return throwError({ error: { message: 'Username "' + newUser.username + '" is already taken' } });
- }
- // save new user
- newUser.id = Object.keys(users).length + 1;
- users.push(newUser);
- localStorage.setItem('users', JSON.stringify(users));
- // respond 200 OK
- return of(new HttpResponse({ status: 200 }));
- }
- // login
- if (request.url.includes(`${environment.API_BASE_URL}${environment.API_Login}`) && request.method === 'POST') {
- // find if any user matches login credentials
- let filteredUsers = users.filter(user => {
- return user.username === request.body.username && user.password === request.body.password;
- });
- if (filteredUsers.length) {
- // if login details are valid return 200 OK with user details and fake jwt token
- let user = filteredUsers[0];
- let body = {
- id: user.id,
- username: user.username,
- token: user.username // We use the username as token to diferentiate which user is authenticated
- };
- return of(new HttpResponse({ status: 200, body: body }));
- } else {
- // else return 400 bad request
- return throwError({ error: { message: 'Username or password is incorrect' } });
- }
- }
- // logout
- if (request.url.includes(`${environment.API_BASE_URL}${environment.API_Logout}`) && request.method === 'POST') {
- // Always return success in this mock
- let body = {};
- return of(new HttpResponse({ status: 200, body: body }));
- }
- // get events
- if (request.url.includes(`${environment.API_BASE_URL}${environment.API_GetAllEvents}`) && request.method === 'GET') {
- if (user) {
- return of(new HttpResponse({ status: 200, body: events }));
- } else {
- // return 401 not authorised if token is null or invalid
- return throwError({ error: { message: 'Unauthorised' } });
- }
- }
- // create event
- if (request.url.includes(`${environment.API_BASE_URL}${environment.API_CreateEvent}`) && request.method === 'POST') {
- if (user) {
- // get new event object from post body
- let newEvent = request.body;
- // validation
- if (!newEvent.description) {
- return throwError({ error: { message: 'Description cannot be empty' } });
- }
- // save new event
- newEvent.id = Object.keys(allEvents).length + 1;
- events.push(newEvent);
- allEvents[username] = events;
- localStorage.setItem('events', JSON.stringify(allEvents));
- // respond 200 OK
- return of(new HttpResponse({ status: 200 }));
- } else {
- // return 401 not authorised if token is null or invalid
- return throwError({ error: { message: 'Unauthorised' } });
- }
- }
- // update event
- if (request.url.includes(`${environment.API_BASE_URL}${environment.API_UpdateEvent}`) && request.method === 'PUT') {
- if (user) {
- // get new event object from post body
- let changedEvent = request.body;
- // validation
- if (!changedEvent.id) {
- return throwError({ error: { message: 'Id cannot be empty' } });
- }
- if (!changedEvent.description) {
- return throwError({ error: { message: 'Description cannot be empty' } });
- }
- // find event by id in events array
- for (let i = 0; i < events.length; i++) {
- if (events[i].id === changedEvent.id) {
- // update event
- events[i] = changedEvent;
- allEvents[username] = events;
- localStorage.setItem('events', JSON.stringify(allEvents));
- break;
- }
- }
- // respond 200 OK
- return of(new HttpResponse({ status: 200 }));
- } else {
- // return 401 not authorised if token is null or invalid
- return throwError({ error: { message: 'Unauthorised' } });
- }
- }
- // remove event
- if (request.url.includes(`${environment.API_BASE_URL}${environment.API_RemoveEvent}`) && request.method === 'DELETE') {
- if (user) {
- // find event by id in events array
- let urlParts = request.url.split('/');
- let id = parseInt(urlParts[urlParts.length - 1]);
- for (let i = 0; i < events.length; i++) {
- let event = events[i];
- if (event.id === id) {
- // delete event
- events.splice(i, 1);
- allEvents[username] = events;
- localStorage.setItem('events', JSON.stringify(allEvents));
- break;
- }
- }
- // respond 200 OK
- return of(new HttpResponse({ status: 200 }));
- } else {
- // return 401 not authorised if token is null or invalid
- return throwError({ error: { message: 'Unauthorised' } });
- }
- }
- // pass through any requests not handled above
- return next.handle(request);
- }))
- // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648)
- .pipe(materialize())
- .pipe(delay(200))
- .pipe(dematerialize());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement