-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
395 lines (350 loc) · 13.9 KB
/
index.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
'use strict';
var _ = require('lodash'),
flow = require('lodash/fp/flow'),
toPairs = require('lodash/fp/toPairs'),
fromPairs = require('lodash/fp/fromPairs'),
map = require('lodash/fp/map'),
defaults = require('lodash/fp/defaults'),
Promise = require('bluebird'),
glob = Promise.promisify(require('glob')),
readFile = Promise.promisify(require('fs').readFile),
XmlParser = require('xml2js').Parser,
xmlParser = Promise.promisifyAll(new XmlParser({ explicitRoot: true, explicitArray: false, mergeAttrs: true })),
fromXml = xmlParser.parseStringAsync,
path = require('path'),
querystring = require('querystring'),
url = require('url'),
sub = require('substituter'),
eql = require('smart-eql'),
_timeout = 60000,
request = require('request-promise'),
_verboseHandlers = {
send: function (opts) {
console.log('SEND%s: %s %s', opts.virtual ? ' [' + opts.virtual + ']' : '', opts.method, opts.uri);
},
sent: function (opts) {
console.log('SENT%s: %s %s [%s ms]', opts.virtual ? ' [' + opts.virtual + ']' : '', opts.method, opts.uri, opts.duration);
},
error: function (opts) {
console.log('ERROR%s: %s %s [%s ms]:', opts.virtual ? ' [' + opts.virtual + ']' : '', opts.method, opts.uri, opts.duration, (opts.error.error || opts.error));
},
debug: function (opts) {
console.log('DEBUG%s: %s %s:', opts.virtual ? ' [' + opts.virtual + ']' : '', opts.method, opts.uri, opts.message);
}
},
// _eventHandlers = _verbosetHandlers,
_root = path.resolve(__dirname + '/virtual'),
_request = request,
_scenarios = {},
_eventHandlers;
if (!RegExp.prototype.toJSON) {
// this allows stringify to work on regular expresssions.
// without this regular expressions are stringified to an empty object
RegExp.prototype.toJSON = RegExp.prototype.toString;
}
function initCall(call) {
let key = call[0],
value = call[1],
parts = key.split(':'),
name = parts[0],
num = parts[1],
files = glob.sync(_root + '/**/' + name + '.*'),
request = {
uri: value.uri,
method: value.method,
qs: value.qs
},
response = {
status: value.status,
delay: value.delay
};
_.forEach(files, function (file) {
if (_.endsWith(file, `.request.${num}.json`)) response.json = file;
else if (_.endsWith(file, '.request.json')) request.json = file;
else if (_.endsWith(file, '.request.xml')) request.xml = file;
else if (_.endsWith(file, '.request.tmpl.json')) request.templateJson = file;
else if (_.endsWith(file, '.request.tmpl.xml')) request.templateXml = file;
else if (_.endsWith(file, `.request.data.${num}.js`)) request.data = require(file);
else if (_.endsWith(file, '.request.data.js')) request.data = request.data || require(file);
else if (_.endsWith(file, `.response.${num}.json`)) response.json = file;
else if (_.endsWith(file, '.response.json')) response.json = file;
else if (_.endsWith(file, '.response.xml')) response.xml = file;
else if (_.endsWith(file, '.response.tmpl.json')) response.templateJson = file;
else if (_.endsWith(file, '.response.tmpl.xml')) response.templateXml = file;
else if (_.endsWith(file, `.response.data.${num}.js`)) response.data = require(file);
else if (_.endsWith(file, '.response.data.js')) response.data = response.data || require(file);
});
return { key: key, value: { request, response } };
}
function initScenario(scenario) {
let key = scenario[0],
value = scenario[1],
calls = flow(
toPairs,
map(initCall)
)(value);
return [key, calls];
}
function renderBody(obj, raw) {
if (obj.json) {
return readFile(obj.json, 'utf8')
.then(function (data) {
return JSON.parse(data);
});
}
if (obj.templateJson) {
return readFile(obj.templateJson, 'utf8').then(function (tmpl) {
return sub(JSON.parse(tmpl), _.isFunction(obj.data) ? obj.data() : obj.data);
});
}
if (obj.xml) {
return readFile(obj.xml, 'utf8')
.then(function (xml) {
return raw ? xml.toString() : fromXml(xml);
});
}
if (obj.templateXml) {
return readFile(obj.templateXml, 'utf8').then(function (xml) {
return raw
? sub(xml, _.isFunction(obj.data) ? obj.data() : obj.data)
: fromXml(xml).then(function (xmlObj) {
return sub(xmlObj, _.isFunction(obj.data) ? obj.data() : obj.data);
});
}
);
}
return Promise.resolve();
}
function render(scenario) {
if (!scenario) return scenario;
return Promise.map(scenario, function (item) {
let call = item.value;
return Promise.all([
renderBody(call.request),
renderBody(call.response, true),
prepareUriObj(call.request)
]).then(function (results) {
return _.merge({}, item, {
value: {
request: { uri: results[2].uri, qs: results[2].qs, body: results[0] },
response: { body: results[1] }
}
});
});
});
}
function prepareBody(opts) {
return _.isString(opts.body)
? fromXml(opts.body)
: Promise.resolve(opts.body);
}
function prepareUriObj(opts) {
// if uri is a regexp, this will not support qs params since ? marks an optional character in regexp
let queryIndex = opts.uri instanceof RegExp ? -1 : opts.uri.indexOf('?');
if (queryIndex !== -1 && !opts.qsString) {
let uriQuery = querystring.parse(opts.uri.slice(queryIndex + 1));
return Promise.resolve({
qs: _.assign({}, opts.qs, uriQuery),
uri: opts.uri.slice(0, queryIndex)
});
} else {
return Promise.resolve({ uri: opts.uri, qs: opts.qs });
}
}
class Vhttp {
constructor(virtual) {
this.virtual = virtual;
}
init() {
let self = this;
if (this.scenario) return Promise.resolve();
return (render(_scenarios[this.virtual]) || Promise.resolve())
.then(function (scenario) {
self.scenario = self.scenario || scenario;
});
}
_findCall(opts) {
return _.find(this.scenario, function (item) {
let call = item.value,
callReq = call.request,
qs = opts.qs,
method = _.trim(opts.method.toUpperCase()),
uri = _.trim(opts.uri.toLowerCase());
if (!call._initialized) {
callReq.method = callReq.method.toUpperCase();
// only convert to lower if it's not a reqexp
callReq.uri = (callReq.uri instanceof RegExp) ? callReq.uri : callReq.uri.toLowerCase();
call._initialized = true;
}
let eq = [
(method === callReq.method),
eql(uri, callReq.uri),
eql(qs, callReq.qs),
eql(opts.preparedBody, callReq.body)
];
opts.message = 'Matching to ' + callReq.method + ':' + callReq.uri +
(callReq.qs ? ('?' + querystring.stringify(callReq.qs)) : '') +
' - method:' + eq[0] +
'; uri:' + eq[1] +
'; qs:' + eq[2] +
'; body:' + eq[3];
if (_eventHandlers && _eventHandlers.debug) {
_eventHandlers.debug(opts);
}
if (eq[0] && eq[1] && !eq[2]) {
opts.error = new Error(
'Query strings do not match for ' + method + ':' + uri +
'\nEXPECTED\n' + JSON.stringify(callReq.qs, null, 4) +
'\nACTUAL\n' + JSON.stringify(qs, null, 4));
if (_eventHandlers && _eventHandlers.error) {
_eventHandlers.error(opts);
}
}
if (eq[0] && eq[1] && !eq[3]) {
opts.error = new Error(
'Bodies do not match for ' + method + ':' + uri +
'\nEXPECTED\n' + JSON.stringify(callReq.body, null, 4) +
'\nACTUAL\n' + JSON.stringify(opts.preparedBody, null, 4));
if (_eventHandlers && _eventHandlers.error) {
_eventHandlers.error(opts);
}
}
return eq[0] && eq[1] && eq[2] && eq[3];
});
}
_sendReal(opts) {
opts.timeout = opts.timeout || _timeout;
return _request(opts)
.then(function (data) {
if (_eventHandlers && _eventHandlers.sent) {
opts.duration = Date.now() - opts.startedAt;
opts.responseBody = data;
_eventHandlers.sent(opts);
}
return data;
})
.catch(function (err) {
if (_eventHandlers && _eventHandlers.error) {
opts.duration = Date.now() - opts.startedAt;
opts.error = err.error || err;
opts.statusCode = err.response && err.response.statusCode;
_eventHandlers.error(opts);
}
throw err;
});
}
_sendVirtual(opts) {
let call = this._findCall(opts);
if (!call) {
let err = new Error('No virtual ' + this.virtual + ' call found for ' + opts.method + ':' + opts.uri);
if (_eventHandlers && _eventHandlers.error) {
opts.duration = Date.now() - opts.startedAt;
opts.error = err;
_eventHandlers.error(opts);
}
return Promise.reject(err);
}
call._called = true;
call = call.value;
let status = call.response.status || 200,
delay = call.response.delay || 0,
responseBody = call.response.body;
if (!status || /^2/.test(status)) {
return Promise
.delay(delay)
.then(function () {
if (_eventHandlers && _eventHandlers.sent) {
opts.duration = Date.now() - opts.startedAt;
opts.responseBody = responseBody;
_eventHandlers.sent(opts);
}
return responseBody;
});
}
return Promise
.delay(delay)
.then(function () {
if (_eventHandlers && _eventHandlers.error) {
opts.duration = Date.now() - opts.startedAt;
opts.error = responseBody;
_eventHandlers.error(opts);
}
return Promise.reject({ error: responseBody });
});
}
send(opts) {
if (_eventHandlers) {
opts.startedAt = Date.now();
}
let self = this,
virtual = this.virtual,
method = opts.method.toUpperCase(),
uri = opts.uri.toLowerCase();
return this.init()
.then(function () {
return Promise.join(prepareUriObj(opts), prepareBody(opts), function (uriObj, body) {
if (self.virtual && !self.scenario) {
let err = new Error('No virtual ' + virtual + ' scenario found for ' + method + ':' + uri);
if (_eventHandlers && _eventHandlers.error) {
opts.error = err;
_eventHandlers.error(opts);
}
throw err;
}
opts.uri = uriObj.uri;
opts.qs = uriObj.qs;
opts.preparedBody = body;
opts.virtual = virtual;
if (_eventHandlers && _eventHandlers.send) {
_eventHandlers.send(opts);
}
return self.scenario
? self._sendVirtual(opts)
: self._sendReal(opts);
});
});
}
done() {
if (!this.virtual || !this.scenario) {
return;
}
var notCalled = _.filter(this.scenario, function (o) {
return !o._called;
});
if (notCalled.length > 0) {
let callErrors = _.map(notCalled, 'key');
throw new Error('The following calls for scenario ' + this.virtual + ' were not made: ' + callErrors.join(', '));
}
}
static configure(opts) {
_root = path.resolve(opts.root || _root);
_timeout = opts.timeout || _timeout;
_request = opts.request || request;
// Use assign for _eventHandlers so that subsequent calls to config can partially override handlers
// for instance one config may set opts.verbose = true, followed by next config includes an eventHandlers
// that only includes an error handler.
if (opts.verbose) _eventHandlers = _.assign(_eventHandlers, _verboseHandlers);
if (opts.eventHandlers || opts.log) {
_eventHandlers = _.assign(_eventHandlers, opts.log, opts.eventHandlers);
}
if (opts.scenarios) this.register(opts.scenarios);
}
static register(scenarios) {
_scenarios = flow(
toPairs,
map(initScenario),
fromPairs,
defaults(_scenarios)
)(scenarios);
}
static reset() {
_scenarios = {};
_request = request;
}
}
_.forEach(['GET', 'POST', 'PATCH', 'DELETE', 'PUT', 'HEAD'], function (verb) {
Vhttp.prototype[verb.toLowerCase()] = function (uri, opts) {
return this.send(_.merge({ method: verb, uri: uri }, opts));
}
});
module.exports = Vhttp;