Advertisement
Guest User

Fake Backend API - DL Angular 6 - 2019

a guest
Jan 30th, 2019
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
  2. import { Injectable } from '@angular/core';
  3. import { Observable, of, throwError } from 'rxjs';
  4. import { delay, dematerialize, materialize, mergeMap } from 'rxjs/operators';
  5. import { environment } from '../../../environments/environment';
  6.  
  7.  
  8. // Based on http://jasonwatmore.com/post/2018/06/22/angular-6-mock-backend-example-for-backendless-development
  9.  
  10.  
  11. @Injectable({
  12.   providedIn: 'root'
  13. })
  14. export class FakeBackendApiInterceptor implements HttpInterceptor {
  15.  
  16.   constructor() { }
  17.  
  18.   intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  19.  
  20.     // array in local storage for registered users
  21.     let users: any[] = JSON.parse(localStorage.getItem('users')) || [];
  22.  
  23.     // array in local storage for registered events
  24.     let allEvents: any[] = JSON.parse(localStorage.getItem('events')) || {};
  25.     let events: any[] = [];
  26.  
  27.  
  28.  
  29.     // add a dummy user with some dummy events
  30.     users[0] = {
  31.       id: 1,
  32.       username: 'dummy',
  33.       password: 'dummy'
  34.     };
  35.     localStorage.setItem('users', JSON.stringify(users));
  36.  
  37.     allEvents['dummy'] = (allEvents && allEvents['dummy'] ? allEvents['dummy'] : []);
  38.     allEvents['dummy'][0] = {
  39.       id: 1,
  40.       description: 'Some event in the future',
  41.       date: new Date(2100, 12, 31),
  42.     };
  43.     allEvents['dummy'][1] = {
  44.       id: 2,
  45.       description: 'Some event in the past',
  46.       date: new Date(1900, 12, 31),
  47.     };
  48.     localStorage.setItem('events', JSON.stringify(allEvents));
  49.  
  50.  
  51.     // get authenticated user from token (if available)
  52.     let username: string = ('' + request.headers.get('Authorization')).replace('Bearer ', '');
  53.     let user: any = null;
  54.     let filteredUsers = users.filter(user => { return user.username === username; });
  55.     if (filteredUsers && filteredUsers.length) {
  56.       user = filteredUsers[0];
  57.       events = (allEvents && allEvents[username] ? allEvents[username] : []);
  58.     }
  59.  
  60.  
  61.  
  62.     // wrap in delayed observable to simulate server api call
  63.     return of(null).pipe(mergeMap(() => {
  64.  
  65.  
  66.  
  67.  
  68.  
  69.       // get current user
  70.       if (request.url.includes(`${environment.API_BASE_URL}${environment.API_GetAuthenticatedUser}`) && request.method === 'GET') {
  71.         // if there is a logged in user return 200 OK with user details and fake jwt token
  72.         if (user) {
  73.           let body = {
  74.             ...user // Copy user details
  75.           };
  76.           return of(new HttpResponse({ status: 200, body: body }));
  77.         } else {
  78.           // return 401 not authorised if token is null or invalid
  79.           return throwError({ error: { message: 'Unauthorised' } });
  80.         }
  81.       }
  82.  
  83.  
  84.  
  85.       // register user
  86.       if (request.url.includes(`${environment.API_BASE_URL}${environment.API_Register}`) && request.method === 'PUT') {
  87.         // get new user object from post body
  88.         let newUser = request.body;
  89.  
  90.         // validation
  91.         if (!newUser.username) {
  92.           return throwError({ error: { message: 'Username cannot be empty' } });
  93.         }
  94.         let duplicateUser = users.filter(user => { return user.username === newUser.username; }).length;
  95.         if (duplicateUser) {
  96.           return throwError({ error: { message: 'Username "' + newUser.username + '" is already taken' } });
  97.         }
  98.  
  99.         // save new user
  100.         newUser.id = Object.keys(users).length + 1;
  101.         users.push(newUser);
  102.         localStorage.setItem('users', JSON.stringify(users));
  103.  
  104.         // respond 200 OK
  105.         return of(new HttpResponse({ status: 200 }));
  106.       }
  107.  
  108.  
  109.  
  110.       // login
  111.       if (request.url.includes(`${environment.API_BASE_URL}${environment.API_Login}`) && request.method === 'POST') {
  112.         // find if any user matches login credentials
  113.         let filteredUsers = users.filter(user => {
  114.           return user.username === request.body.username && user.password === request.body.password;
  115.         });
  116.  
  117.         if (filteredUsers.length) {
  118.           // if login details are valid return 200 OK with user details and fake jwt token
  119.           let user = filteredUsers[0];
  120.           let body = {
  121.             id: user.id,
  122.             username: user.username,
  123.             token: user.username // We use the username as token to diferentiate which user is authenticated
  124.           };
  125.  
  126.           return of(new HttpResponse({ status: 200, body: body }));
  127.         } else {
  128.           // else return 400 bad request
  129.           return throwError({ error: { message: 'Username or password is incorrect' } });
  130.         }
  131.       }
  132.  
  133.  
  134.  
  135.       // logout
  136.       if (request.url.includes(`${environment.API_BASE_URL}${environment.API_Logout}`) && request.method === 'POST') {
  137.         // Always return success in this mock
  138.         let body = {};
  139.         return of(new HttpResponse({ status: 200, body: body }));
  140.       }
  141.  
  142.  
  143.  
  144.  
  145.  
  146.  
  147.       // get events
  148.       if (request.url.includes(`${environment.API_BASE_URL}${environment.API_GetAllEvents}`) && request.method === 'GET') {
  149.         if (user) {
  150.           return of(new HttpResponse({ status: 200, body: events }));
  151.         } else {
  152.           // return 401 not authorised if token is null or invalid
  153.           return throwError({ error: { message: 'Unauthorised' } });
  154.         }
  155.       }
  156.  
  157.  
  158.  
  159.       // create event
  160.       if (request.url.includes(`${environment.API_BASE_URL}${environment.API_CreateEvent}`) && request.method === 'POST') {
  161.         if (user) {
  162.  
  163.           // get new event object from post body
  164.           let newEvent = request.body;
  165.  
  166.           // validation
  167.           if (!newEvent.description) {
  168.             return throwError({ error: { message: 'Description cannot be empty' } });
  169.           }
  170.  
  171.           // save new event
  172.           newEvent.id = Object.keys(allEvents).length + 1;
  173.           events.push(newEvent);
  174.           allEvents[username] = events;
  175.           localStorage.setItem('events', JSON.stringify(allEvents));
  176.  
  177.           // respond 200 OK
  178.           return of(new HttpResponse({ status: 200 }));
  179.  
  180.         } else {
  181.           // return 401 not authorised if token is null or invalid
  182.           return throwError({ error: { message: 'Unauthorised' } });
  183.         }
  184.       }
  185.  
  186.  
  187.  
  188.  
  189.  
  190.  
  191.  
  192.       // update event
  193.       if (request.url.includes(`${environment.API_BASE_URL}${environment.API_UpdateEvent}`) && request.method === 'PUT') {
  194.         if (user) {
  195.  
  196.           // get new event object from post body
  197.           let changedEvent = request.body;
  198.  
  199.           // validation
  200.           if (!changedEvent.id) {
  201.             return throwError({ error: { message: 'Id cannot be empty' } });
  202.           }
  203.           if (!changedEvent.description) {
  204.             return throwError({ error: { message: 'Description cannot be empty' } });
  205.           }
  206.  
  207.           // find event by id in events array
  208.           for (let i = 0; i < events.length; i++) {
  209.             if (events[i].id === changedEvent.id) {
  210.               // update event
  211.               events[i] = changedEvent;
  212.               allEvents[username] = events;
  213.               localStorage.setItem('events', JSON.stringify(allEvents));
  214.               break;
  215.             }
  216.           }
  217.  
  218.           // respond 200 OK
  219.           return of(new HttpResponse({ status: 200 }));
  220.  
  221.         } else {
  222.           // return 401 not authorised if token is null or invalid
  223.           return throwError({ error: { message: 'Unauthorised' } });
  224.         }
  225.       }
  226.  
  227.  
  228.  
  229.       // remove event
  230.       if (request.url.includes(`${environment.API_BASE_URL}${environment.API_RemoveEvent}`) && request.method === 'DELETE') {
  231.         if (user) {
  232.           // find event by id in events array
  233.           let urlParts = request.url.split('/');
  234.           let id = parseInt(urlParts[urlParts.length - 1]);
  235.           for (let i = 0; i < events.length; i++) {
  236.             let event = events[i];
  237.             if (event.id === id) {
  238.               // delete event
  239.               events.splice(i, 1);
  240.               allEvents[username] = events;
  241.               localStorage.setItem('events', JSON.stringify(allEvents));
  242.               break;
  243.             }
  244.           }
  245.  
  246.           // respond 200 OK
  247.           return of(new HttpResponse({ status: 200 }));
  248.         } else {
  249.           // return 401 not authorised if token is null or invalid
  250.           return throwError({ error: { message: 'Unauthorised' } });
  251.         }
  252.       }
  253.  
  254.  
  255.  
  256.  
  257.  
  258.       // pass through any requests not handled above
  259.       return next.handle(request);
  260.  
  261.     }))
  262.  
  263.       // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648)
  264.       .pipe(materialize())
  265.       .pipe(delay(200))
  266.       .pipe(dematerialize());
  267.   }
  268. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement