-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (50 loc) · 1.54 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
const EventEmitter = require('events')
class MockResponse extends EventEmitter {
description () {
return 'Mock a response for any given request.'
}
optionDefinitions () {
return [
{
name: 'mocks',
multiple: true,
typeLabel: '{underline file} {underline ...}',
description: 'One or more modules exporting Mock Responses.'
}
]
}
middleware (options) {
const arrayify = require('array-back')
const path = require('path')
const mockResponse = require('koa-mock-response')
const loadModule = require('load-module')
let mocks = arrayify(options.mocks)
if (mocks && mocks.length) {
const flatten = require('reduce-flatten')
mocks = mocks
.map(mockPath => {
return typeof mockPath === 'string' ? loadModule(mockPath, { paths: '.' }) : mockPath
})
.reduce(flatten, [])
const mockInstances = mocks
.map(Mock => {
let mock = new Mock()
if (mock.on) {
mock.on('verbose', (key, value) => {
this.emit('verbose', key, value)
})
}
return mock
})
this.emit('verbose', 'middleware.mock-response.config', { mocks: mockInstances })
/* return an array of middleware */
return mockInstances
.map(mock => {
const mockResponses = arrayify(mock.mocks(options))
return mockResponses.map(mock => mockResponse(mock.route, mock.responses))
})
.reduce(flatten, [])
}
}
}
module.exports = MockResponse