Advertisement
Guest User

Untitled

a guest
Mar 13th, 2017
503
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 mockBackEndFactory(backend: MockBackend, options: BaseRequestOptions) {
  5.   // configure fake backend
  6.   backend.connections.subscribe((connection: MockConnection) => {
  7.     let testUser = {
  8.       id: "123",
  9.       username: "john.doe@gmail.com",
  10.       password: "johnpasswd",
  11.       name: "John DOE",
  12.       givenName: "John",
  13.       familyName: "DOE",
  14.       email: "john.doe@gmail.com"
  15.     };
  16.  
  17.     // wrap in timeout to simulate server api call
  18.     setTimeout(() => {
  19.  
  20.       // fake authenticate api end point
  21.       if (connection.request.url.endsWith('/api/authenticate') && connection.request.method === RequestMethod.Post) {
  22.         // get parameters from post request
  23.         let params = JSON.parse(connection.request.getBody());
  24.  
  25.         // check user credentials and return fake jwt token if valid
  26.         if (params.username === testUser.username && params.password === testUser.password) {
  27.           connection.mockRespond(new Response(
  28.             new ResponseOptions({status: 200, body: {token: 'fake-jwt-token'}})
  29.           ));
  30.         } else {
  31.           connection.mockRespond(new Response(
  32.             new ResponseOptions({status: 200})
  33.           ));
  34.         }
  35.       }
  36.  
  37.       // fake users api end point
  38.       if (connection.request.url.endsWith('/api/users') && connection.request.method === RequestMethod.Get) {
  39.         // check for fake auth token in header and return test users if valid, this security is implemented server side
  40.         // in a real application
  41.         if (connection.request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
  42.           connection.mockRespond(new Response(
  43.             new ResponseOptions({status: 200, body: [testUser]})
  44.           ));
  45.         } else {
  46.           // return 401 not authorised if token is null or invalid
  47.           connection.mockRespond(new Response(
  48.             new ResponseOptions({status: 401})
  49.           ));
  50.         }
  51.       }
  52.  
  53.     }, 500);
  54.  
  55.   });
  56.  
  57.   return new Http(backend, options);
  58. }
  59.  
  60. export let fakeBackendProvider = {
  61.   // use fake backend in place of Http service for backend-less development
  62.   provide: Http,
  63.   deps: [MockBackend, BaseRequestOptions],
  64.   useFactory: mockBackEndFactory
  65. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement