-
Notifications
You must be signed in to change notification settings - Fork 20
/
request.js
369 lines (323 loc) · 8.81 KB
/
request.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
'use strict';
var fs = require('fs'),
qs = require('querystring'),
url_ = require('url'),
Stream = require('stream'),
urlEqual = require('url-equal'),
deepEqual = require('deep-equal');
// From Nock
function isStream(obj) {
return obj &&
(typeof a !== 'string') &&
(! Buffer.isBuffer(obj)) &&
typeof obj.setEncoding === 'function';
}
function bodyEqual(a, b) {
if (typeof a === 'object' && typeof b === 'object' && a !== null && b !== null) {
return deepEqual(a, b);
}
else {
return a === b;
}
}
function createResponse(request, response) {
var self = this;
var headers = typeof this.response.headers === 'function' ? this.response.headers(request) : this.response.headers || this._defaultReplyHeaders;
this.response.body = typeof this.response.body === 'function' ? this.response.body(request) : this.response.body;
response.writeHead(this.response.statusCode, headers);
if (isStream(this.response.body)) {
var readStream = this.response.body;
if (this._maxRequests > 1) {
// Because we need to respond with this body more than once, if it is a stream,
// we make a buffer copy and use that as the body for future responses.
var data = [];
readStream.on('readable', function () {
var chunk;
while (null !== (chunk = readStream.read())) {
data.push(chunk);
response.write(chunk);
}
});
readStream.on('end', function(){
self.response.body = Buffer.concat(data);
response.end();
});
}
else {
readStream.pipe(response);
}
}
else if ((typeof this.response.body === 'object') && !Buffer.isBuffer(this.response.body)) {
response.end(JSON.stringify(this.response.body));
}
else {
response.end(this.response.body);
}
return this.shouldPrune();
};
/**
* Request class
*
* @description This is the Request class for Hock. It represents a single request,
* and the response to that request
*
* @param {object} parent the hock server this request belongs to
* @param {object} options
* @param {String} options.url the route for the current request i.e. /foo/bar
* @param {String|object} [options.body] optional request body
*
* @param {object} [options.headers] optional request headers
* @param {object} [options.method] the method for the request (default=GET)
*
* @type {Function}
*/
var Request = module.exports = function (parent, options) {
var self = this;
this.method = options.method || 'GET';
this.url = options.url;
this.body = options.body || '';
this.headers = options.headers || {};
Object.keys(this.headers).forEach(function (key) {
self.headers[key.toLowerCase()] = self.headers[key];
if (key.toLowerCase() !== key) {
delete self.headers[key];
}
});
this._defaultReplyHeaders = {};
this._parent = parent;
this._minRequests = 1;
this._maxRequests = 1;
this._count = 0;
this._delay = 0;
};
/**
* Request.reply
*
* @description provide the mocked reply for the current request
*
* @param {Number} [statusCode] Status Code for the response (200)
* @param {String|object} [body] The body for the response
* @param {object} [headers] Headers for the response
* @returns {*}
*/
Request.prototype.reply = function (statusCode, body, headers) {
this.response = {
statusCode: statusCode || 200,
body: body || '',
headers: headers
};
this._parent.enqueue(this);
return this._parent;
};
/**
* Request.replyWithFile
*
* @description provide the mocked reply for the current request based on an input file
*
* @param {Number} statusCode Status Code for the response (200)
* @param {String} filePath The path of the file to respond with
* @param {object} [headers] Headers for the response
* @returns {*}
*/
Request.prototype.replyWithFile = function (statusCode, filePath, headers) {
this.response = {
statusCode: statusCode || 200,
body: fs.createReadStream(filePath),
headers: headers
};
this._parent.enqueue(this);
return this._parent;
};
/**
* Request.many
*
* @decsription allow a request to match multiple queries at the same url.
*
* @param {object} [options] (default={min: 1, max: infinity})
* @param {object} [options.min] minimum requests to be matched
* @param {object} [options.max] max requests to be matched, must be >= min.
* @returns {Request}
*/
Request.prototype.many = function(options) {
options = options || {
min: 1,
max: Infinity
};
if (typeof options.min === 'number') {
this._minRequests = options.min;
if (this._minRequests > this._maxRequests) {
this._maxRequests = this._minRequests;
}
}
if (typeof options.max === 'number') {
this._maxRequests = options.max;
}
return this;
};
/**
* Request.min
*
* @description convenience function to provide a number for minimum requests
*
* @param {Number} number the value for min
* @returns {Request}
*/
Request.prototype.min = function(number) {
return this.many({ min: number });
};
/**
* Request.max
*
* @description convenience function to provide a number for maximum requests
*
* @param {Number} number the value for max
* @returns {Request}
*/
Request.prototype.max = function (number) {
return this.many({ max: number });
};
/**
* Request.once
*
* @description convenience function to set min, max to 1
*
* @returns {Request}
*/
Request.prototype.once = function() {
return this.many({ min: 1, max: 1 });
};
/**
* Request.twice
*
* @description convenience function to set min, max to 2
*
* @returns {Request}
*/
Request.prototype.twice = function() {
return this.many({ min: 1, max: 2 });
}
/**
* Request.any
*
* @description convenience function to set min 0, max to Infinity
*
* @returns {Request}
*/
Request.prototype.any = function() {
return this.many({ min: 0, max: Infinity });
}
/**
* Request.delay
*
* @description Delays the requests by number of ms
*
* @returns {boolean}
*/
Request.prototype.delay = function(ms) {
this._delay = ms;
return this;
};
/**
* Request.isMatch
*
* @description identify if the current request matches the provided request
*
* @param {object} request The request from the Hock server
*
* @returns {boolean|*}
*/
Request.prototype.isMatch = function(request) {
var self = this;
if (this._parent._pathFilter) {
request.url = this._parent._pathFilter(request.url);
}
if (request.method === 'GET' || request.method === 'DELETE') {
return this.method === request.method && urlEqual(this.url, request.url) &&
checkHeaders();
}
else {
let body = request.body;
if (this._requestFilter) {
body = this._requestFilter(request.body);
}
if (typeof this.body === 'object') {
try {
body = JSON.parse(body)
}
catch (err) {
}
}
return this.method === request.method && urlEqual(this.url, request.url) &&
bodyEqual(this.body, body) && checkHeaders();
}
function checkHeaders() {
var match = true;
Object.keys(self.headers).forEach(function (key) {
if (self.headers[key] && self.headers[key] !== request.headers[key]) {
match = false;
}
});
return match;
}
};
/**
* Request.sendResponse
*
* @description send the response to the provided Hock response. Applies a delay if it was set
*
* @param {object} request The request object from the hock server
* @param {object} response The response object from the hock server
*/
Request.prototype.sendResponse = function(request, response) {
var self = this;
this._count++;
if (this._delay > 0) {
setTimeout(function() {
createResponse.call(self, request, response);
}, this._delay);
}
else {
createResponse.call(this, request, response);
}
return this.shouldPrune();
}
/**
* Request.isDone
*
* @description Identify if the current request has met its min and max requirements
*
* @returns {boolean}
*/
Request.prototype.isDone = function() {
return !(this._count >= this._minRequests && this._count <= this._maxRequests);
};
/**
* Request.shouldPrune
*
* @description Identify if the request has met its max requirement
*
* @returns {boolean}
*/
Request.prototype.shouldPrune = function() {
return this._count >= this._maxRequests;
};
/**
* Request.toJSON
*
* @returns {{method: *, url: *, body: *, headers: *, stats: {count: number, min: (Function|*|Object), max: *, isValid: *, shouldPrune: *}}}
*/
Request.prototype.toJSON = function() {
return {
method: this.method,
url: this.url,
body: this.body,
headers: this.headers,
stats: {
count: this._count,
min: this._minRequests,
max: this._maxRequests,
isDone: this.isDone(),
shouldPrune: this.shouldPrune()
}
};
};