Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http';
  2. import { MockBackend, MockConnection } from '@angular/http/testing';
  3.  
  4. export function fakeBackendFactory(backend: MockBackend, options: BaseRequestOptions) {
  5.   // configure fake backend
  6.   backend.connections.subscribe((connection: MockConnection) => {
  7.     let testUser = { username: 'test1', password: 'test', firstName: 'Test', lastName: 'User' };
  8.  
  9.     // wrap in timeout to simulate server api call
  10.     setTimeout(() => {
  11.  
  12.       // fake authenticate api end point
  13.       if (connection.request.url.endsWith('/api/authenticate') && connection.request.method === RequestMethod.Post) {
  14.         // get parameters from post request
  15.         let params = JSON.parse(connection.request.getBody());
  16.  
  17.         // check user credentials and return fake jwt token if valid
  18.         if (params.username === testUser.username && params.password === testUser.password) {
  19.           connection.mockRespond(new Response(
  20.             new ResponseOptions({ status: 200, body: { token: 'fake-jwt-token' } })
  21.           ));
  22.         } else {
  23.           connection.mockRespond(new Response(
  24.             new ResponseOptions({ status: 200 })
  25.           ));
  26.         }
  27.       }
  28.  
  29.       // fake users api end point
  30.       if (connection.request.url.endsWith('/api/users') && connection.request.method === RequestMethod.Get) {
  31.         // check for fake auth token in header and return test users if valid, this security is implemented server side
  32.         // in a real application
  33.         if (connection.request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
  34.           connection.mockRespond(new Response(
  35.             new ResponseOptions({ status: 200, body: [testUser] })
  36.           ));
  37.         } else {
  38.           // return 401 not authorised if token is null or invalid
  39.           connection.mockRespond(new Response(
  40.             new ResponseOptions({ status: 401 })
  41.           ));
  42.         }
  43.       }
  44.  
  45.     }, 500);
  46.  
  47.   });
  48.  
  49.   return new Http(backend, options);
  50. }
  51.  
  52. export let fakeBackendProvider = {
  53.   // use fake backend in place of Http service for backend-less development
  54.   provide: Http,
  55.   useFactory: fakeBackendFactory,
  56.   deps: [MockBackend, BaseRequestOptions]
  57. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement