-
Notifications
You must be signed in to change notification settings - Fork 137
/
in-memory-data.service.ts
195 lines (174 loc) · 4.82 KB
/
in-memory-data.service.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
/**
* Hero-oriented InMemoryDbService with method overrides.
*/
import { Injectable } from '@angular/core';
import {
RequestInfo,
RequestInfoUtilities,
ParsedRequestUrl,
ResponseOptions,
STATUS
} from 'angular-in-memory-web-api';
import { ChangeSet } from 'ngrx-data';
/** In-memory database data */
interface Db {
[collectionName: string]: any[];
}
@Injectable()
export class InMemoryDataService {
/** True if in-mem service is intercepting; all requests pass thru when false. */
active = true;
maxId = 0;
/** In-memory database data */
db: Db = {};
/** Create the in-memory database on start or by command */
createDb(reqInfo?: RequestInfo) {
this.db = getDbData();
if (reqInfo) {
const body = reqInfo.utils.getJsonBody(reqInfo.req) || {};
if (body.clear === true) {
// tslint:disable-next-line:forin
for (const coll in this.db) {
this.db[coll].length = 0;
}
}
this.active = !!body.active;
}
return this.db;
}
/**
* Simulate generating new Id on the server
* All collections in this db have numeric ids.
* Seed grows by highest id seen in any of the collections.
*/
genId(collection: { id: number }[], collectionName: string) {
this.maxId = 1 + collection.reduce((prev, cur) => Math.max(prev, cur.id || 0), this.maxId);
return this.maxId;
}
/**
* Override `parseRequestUrl`
* Manipulates the request URL or the parsed result.
* If in-mem is inactive, clear collectionName so that service passes request thru.
* If in-mem is active, after parsing with the default parser,
* @param url from request URL
* @param utils for manipulating parsed URL
*/
parseRequestUrl(url: string, utils: RequestInfoUtilities): ParsedRequestUrl {
const parsed = utils.parseRequestUrl(url);
parsed.collectionName = this.active ? mapCollectionName(parsed.collectionName) : undefined;
return parsed;
}
/**
* Special-cases for POST methods
*/
post(req: RequestInfo) {
if (req.url.endsWith('/save/delete-villains')) {
return this.mockDeleteVillains(req);
}
// Let all other POST requests through
return null;
}
private mockDeleteVillains(requestInfo: RequestInfo) {
const originalRequest = requestInfo.req as any;
const changeSet: ChangeSet = originalRequest.body;
const changes = changeSet.changes;
changes.forEach(item => {
// Only know how to delete villains
if (item.entityName === 'Villain') {
const deleteIds = item.entities as number[];
this.db['villains'] = this.db['villains'].filter(v => !deleteIds.includes(v.id));
}
});
// In this example, the server processes the request
// w/o changing the data that it inserts or updates.
// There's no reason to expect the server to return anything.
// So this API responds with 204-No Content and no body.
const options: ResponseOptions = {
url: requestInfo.url,
status: STATUS.NO_CONTENT,
statusText: 'NO CONTENT',
body: null
};
// But if it did return updated entities it might respond with this
// const options: ResponseOptions = {
// url: requestInfo.url,
// status: STATUS.OK,
// statusText: 'OK',
// body: changeSet
// };
return requestInfo.utils.createResponse$(() => options);
}
}
/**
* Remap a known singular collection name ("hero")
* to the plural collection name ("heroes"); else return the name
* @param name - collection name from the parsed URL
*/
function mapCollectionName(name: string): string {
return (
({
hero: 'heroes',
villain: 'villains'
} as any)[name] || name
);
}
/**
* Development data
*/
function getDbData() {
const heroes: any[] = [
{
id: 11,
name: 'Maxwell Smart',
saying: 'Missed it by that much.'
},
{
id: 12,
name: 'Bullwinkle J. Moose',
saying: 'Watch me pull a rabbit out of a hat.'
},
{
id: 13,
name: 'Muhammad Ali',
saying: 'Float like a butterfly, sting like a bee.'
},
{
id: 14,
name: 'Eleanor Roosevelt',
saying: 'No one can make you feel inferior without your consent.'
}
];
const villains: any[] = [
{
id: 21,
name: 'Dr. Evil',
saying: 'One million dollars!'
},
{
id: 22,
name: 'Agent Smith',
saying: 'Human beings are a disease.'
},
{
id: 23,
name: 'Natasha Fatale',
saying: 'You can say that again, dahling.'
},
{
id: 24,
name: 'Goldfinger',
saying: 'No, I expect you to die!'
},
{
id: 25,
name: 'West Witch',
saying: `I'll get you, my pretty, and your little dog too!`
},
{
id: 26,
name: 'Tony Montana',
saying: 'Say hello to my little friend.'
}
];
return { heroes, villains } as Db;
}