-
Notifications
You must be signed in to change notification settings - Fork 3
/
demock.js
323 lines (280 loc) · 11.4 KB
/
demock.js
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([ 'module' ], function (module) {
module.exports = factory();
});
} else if (typeof module === 'object') {
module.exports = factory();
} else {
root.Demock = factory();
}
}(this, function () {
'use strict';
function getPropertyByPath(object, path) {
if (path) {
var tokens = path.split('.');
while (object && tokens.length) {
object = object[tokens.shift()];
}
}
return object;
}
function setPropertyByPath(object, path, value) {
if (path) {
var tokens = path.split('.');
while (object && tokens.length > 1) {
object = object[tokens.shift()];
}
object[tokens[0]] = value;
}
}
function Demock() {
var requestFilters = [],
responseFilters = [],
logFn;
this.appendRequestFilter = function (filter) {
requestFilters.push(filter);
return this;
};
this.appendResponseFilter = function (filter) {
responseFilters.push(filter);
return this;
};
this.setLogger = function (newLogFn) {
logFn = newLogFn;
};
/**
* Run all request filters on the given request object.
*
* @param {Object} request - The request object with properties:
* method - The request method (uppercase: GET, POST, ...)
* url - The request URL
* headers - The request headers
* params - The request parameters (query string or body)
*/
this.filterRequest = function (request) {
requestFilters.forEach(function (filter) {
filter(request, logFn);
});
};
/**
* @param {Object} request - Same as in #filterRequest
* @param {Object} response - The response object with properties:
* statusCode - The HTTP status code (200, 400, etc.)
* statusText - The HTTP status text (OK, Bad Request, etc.)
* Optional.
* headers - The response headers
* data - The response data.
*/
this.filterResponse = function (request, response) {
responseFilters.forEach(function (filter) {
filter(request, response, logFn);
});
if (response.data && response.data.hasOwnProperty('$data')) {
response.data = response.data.$data;
this.filterResponse(request, response);
}
};
}
/**
* Stock request filters
*/
Demock.requestFilters = {
/**
* Converts all methods to GET by appending the original method name to the request URL
*/
method: function () {
return function (request) {
if (request.method !== 'GET') {
request.headers = request.headers || {};
request.headers['X-MethodFilter-Original-URL'] = request.url;
request.headers['X-MethodFilter-Original-Method'] = request.method;
request.url = request.url.replace(/\/?$/, '/') + request.method + '/';
request.method = 'GET';
for (var paramName in request.params) {
request.headers['X-MethodFilter-Request-Param-' + paramName] = request.params[paramName];
}
}
};
},
/**
* Appends the default document name to the request URL
*/
defaultDocument: function (config) {
return function (request) {
if (config.urlPrefix && request.url.indexOf(config.urlPrefix) !== 0) {
return;
}
request.headers = request.headers || {};
request.headers['X-DefaultDocumentFilter-Original-URL'] = request.url;
request.url = request.url.replace(/\/?$/, '/' + config.defaultDocument);
};
},
requestSummary: function () {
return function (request, logFn) {
if (logFn) {
logFn('[requestSummary]', request.method, request.url, request.params);
}
};
}
};
/**
* Stock response filters
*/
Demock.responseFilters = {
/**
* Delays the response by the specified milliseconds
*/
delay: function () {
return function (request, response) {
if (response.data && response.data.$delay) {
response.delay = response.data.$delay;
}
};
},
/**
* Overrides the HTTP response status code and status text
*/
status: function () {
return function (request, response) {
if (response.data && response.data.$status) {
response.statusCode = response.data.$status.code || response.statusCode;
response.statusText = response.data.$status.text || response.statusText;
}
};
},
/**
* Simulates a connection timeout
*/
timeout: function () {
return function (request, response) {
if (response.data && response.data.$timeout) {
response.timeout = true;
}
};
},
/**
* Picks a response based on the specified property's values
* Relies on $case and $default properties
*/
'switch': function () {
return function (request, response) {
if (response.data && response.data.$switch) {
var cases = response.data.$case,
paramValue = request.params && request.params[response.data.$switch];
if (cases && cases.hasOwnProperty(paramValue)) {
response.data = { $data: cases[paramValue] };
return;
}
response.data = { $data: response.data.$default };
}
};
},
arrayFilter: function () {
var matchers = {
'=': function (paramValue, propValue) {
return '' + paramValue === '' + propValue;
},
'<=': function (paramValue, propValue) {
return paramValue <= propValue;
},
'>=': function (paramValue, propValue) {
return paramValue >= propValue;
},
']': function (paramValue, propValue) {
return paramValue.indexOf(propValue) >= 0;
}
};
return function (request, response) {
if (response.data && response.data.$arrayFilter) {
var array = getPropertyByPath(response.data.$data, response.data.$arrayPath);
if (array instanceof Array && request.params) {
var filtered = array.filter(function (item) {
for (var paramName in response.data.$arrayFilter) {
if (request.params.hasOwnProperty(paramName)) {
var filter = response.data.$arrayFilter[paramName],
tokens = /^(=|<=|>=|])(.+)?$/.exec(filter);
if (!tokens) {
throw 'Invalid filter syntax ' + filter;
}
var propName = tokens[2] || paramName,
matcher = matchers[tokens[1]];
if (!matcher(request.params[paramName], item[propName])) {
return false;
}
}
}
return true;
});
array.length = 0;
array.push.apply(array, filtered);
}
}
};
},
arraySort: function () {
return function (request, response) {
if (response.data && response.data.$arraySort) {
var array = getPropertyByPath(response.data.$data, response.data.$arrayPath);
if (array instanceof Array && request.params && request.params.sortKey) {
array.sort(function (a, b) {
return ('' + a[request.params.sortKey]).localeCompare(
'' + b[request.params.sortKey]
) * (request.params.sortDir === 'ASC' ? 1 : -1);
});
}
}
};
},
arrayWhenEmpty: function () {
return function (request, response) {
if (response.data && response.data.hasOwnProperty('$arrayWhenEmpty')) {
var array = getPropertyByPath(response.data.$data, response.data.$arrayPath);
if (array instanceof Array && !array.length) {
response.data.$data = response.data.$arrayWhenEmpty;
}
}
};
},
arrayItem: function () {
return function (request, response) {
if (response.data && response.data.hasOwnProperty('$arrayItem')) {
var array = getPropertyByPath(response.data.$data, response.data.$arrayPath);
if (array instanceof Array) {
var value;
switch (response.data.$arrayItem) {
case 'random':
value = array[Math.floor(array.length * Math.random())];
break;
default:
value = array[response.data.$arrayItem];
break;
}
if (response.data.$arrayPath) {
setPropertyByPath(response.data.$data, response.data.$arrayPath, value);
} else {
response.data.$data = value;
}
}
}
};
},
doc: function () {
return function (request, response, logFn) {
if (logFn && response.data && response.data.$doc) {
response.data.$doc.forEach(function (text) {
logFn('[doc]', '(' + request.url + ')', text);
});
}
};
},
responseSummary: function () {
return function (request, response, logFn) {
if (logFn && response.data && !response.data.$data) {
logFn('[responseSummary]', request.url, response.statusCode, response.data);
}
};
}
};
return Demock;
}));