-
Notifications
You must be signed in to change notification settings - Fork 8
/
fake-backend.ts
55 lines (47 loc) · 2.58 KB
/
fake-backend.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
export let fakeBackendProvider = {
// use fake backend in place of Http service for backend-less development
provide: Http,
useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
// configure fake backend
backend.connections.subscribe((connection: MockConnection) => {
let testUser = { username: 'test', password: 'test', firstName: 'Test', lastName: 'User' };
// wrap in timeout to simulate server api call
setTimeout(() => {
// fake authenticate api end point
if (connection.request.url.endsWith('/api/authenticate') && connection.request.method === RequestMethod.Post) {
// get parameters from post request
let params = JSON.parse(connection.request.getBody());
// check user credentials and return fake jwt token if valid
if (params.username === testUser.username && params.password === testUser.password) {
connection.mockRespond(new Response(
new ResponseOptions({ status: 200, body: { token: 'fake-jwt-token' } })
));
} else {
connection.mockRespond(new Response(
new ResponseOptions({ status: 200 })
));
}
}
// fake users api end point
if (connection.request.url.endsWith('/api/users') && connection.request.method === RequestMethod.Get) {
// check for fake auth token in header and return test users if valid, this security is implemented server side
// in a real application
if (connection.request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
connection.mockRespond(new Response(
new ResponseOptions({ status: 200, body: [testUser] })
));
} else {
// return 401 not authorised if token is null or invalid
connection.mockRespond(new Response(
new ResponseOptions({ status: 401 })
));
}
}
}, 500);
});
return new Http(backend, options);
},
deps: [MockBackend, BaseRequestOptions]
};