-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
226 lines (208 loc) · 6.12 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
'use strict'
const http = require('http')
const isFunction = require('101/is-function')
const isNumber = require('101/is-number')
const isObject = require('101/is-object')
const isString = require('101/is-string')
const isRegExp = require('101/is-regexp')
const keypather = require('keypather')()
const noop = require('101/noop')
const sinon = require('sinon')
const debug = require('debug')
const debugInit = debug('mehpi:init')
const debugInitError = debug('mehpi:init:error')
const debugSetup = debug('mehpi:setup')
const debugSetupError = debug('mehpi:setup:error')
const debugRespone = debug('mehpi:response')
const debugResponeError = debug('mehpi:response:error')
const PRIORITY_LIMIT = 100
const PRIORITY_DEFAULT = 10
/**
* Mock API server. Allows one to mock any api and setup stubs for particlar
* routes (via sinon).
* @author Ryan Sandor Richards
*/
module.exports = class MockAPI {
/**
* Creates a new mock api server.
* @param {Integer} port The port for the api server.
*/
constructor (port) {
this.port = port
this.restore()
this.server = http.createServer(this._handler.bind(this))
this.routeStubs = {
'text': {},
'regex': []
}
// Have the mock always return a 200 on index
this.setStub('GET', '/')
}
/**
* Starts the mock api server.
* @param {function} done Callback to execute once the server is listening.
*/
start (done) {
if (!isFunction(done)) {
done = noop
}
this.server.listen(this.port, (err) => {
if (err) {
debugInitError(`Failed to start server (port: ${this.port}) / ${err.message}`)
done(err)
return
}
debugInit(`Server listening (port: ${this.port})`)
done()
})
}
/**
* Stops the mock api server.
* @param {function} done Callback to execute once the server is stopped.
*/
stop (done) {
if (!isFunction(done)) {
done = noop
}
this.server.close((err) => {
debugInit(`Server stopped (port: ${this.port})`)
done(err)
})
}
/**
* Handles incoming requests to the mock server. This will call stub methods
* appropriately.
*/
_handler (request, response) {
const method = request.method
const path = request.url
const routeStub = this.getStub(method, path)
if (!routeStub) {
return this.stubNotFound(response)
}
const result = routeStub(request, response)
debugRespone(`Request: ${method} ${path}`)
let status = 200
let body = 'response'
let contentType = 'text/plain'
if (isNumber(result)) {
status = result
} else if (isString(result)) {
body = result
} else if (isObject(result)) {
if (isNumber(result.status)) {
status = result.status
}
if (isObject(result.body) || Array.isArray(result.body)) {
contentType = 'application/json'
body = JSON.stringify(result.body)
} else if (result.body) {
body = result.body.toString()
}
}
debugRespone(`Response: ${status} ${body} (${contentType})`)
response.writeHead(status, { 'Content-Type': contentType })
response.end(body)
}
getStub (method, path) {
if (!path) {
path = method
method = 'GET'
}
method = method.toUpperCase()
const key = `${method} ${path}`
let textStub = keypather.get(this.routeStubs.text, key)
if (textStub) {
debugRespone(`Found string match: ${method} ${path}`)
return textStub
}
// Check all regular expressions
for (var i = PRIORITY_LIMIT; i >= 0; i -= 1) {
if (Array.isArray(this.routeStubs.regex[i])) {
for (let entry of this.routeStubs.regex[i]) {
if (path.match(entry.regex)) {
debugRespone(`Found regular expression: ${method} ${path} ${entry.regex}`)
return entry.stub
}
}
}
}
return null
}
/**
* Returns the stub method for a route on the server.
* @param {string} [method] HTTP Method for the request stub (ex: PUT, POST).
* @param {string} path Path to stub (ex: /users/me)
*/
setStub (method, path, priority) {
if (!path) {
path = method
method = 'GET'
}
method = method.toUpperCase()
if (isString(path)) {
const key = `${method} ${path}`
let textStub = keypather.get(this.routeStubs, `text.${method}.${path}`)
if (!textStub) {
this.routeStubs.text[key] = sinon.stub()
// throw new Error('Stub already declared')
}
debugSetup(`String stub added: ${path}`)
return this.routeStubs.text[key]
}
if (isRegExp(path)) {
if (priority > PRIORITY_LIMIT) {
throw new Error(`'priority' must be under ${PRIORITY_LIMIT}`)
}
if (priority === undefined) {
priority = PRIORITY_DEFAULT
}
if (!isNumber(priority)) {
throw new Error('\'priority\' is not a number')
}
let newStub = sinon.stub()
if (!this.routeStubs.regex[priority]) {
this.routeStubs.regex[priority] = []
}
// Replace same regex if found
let regexKeys = this.routeStubs.regex[priority].map(x => x.regex.toString())
if (regexKeys.indexOf(path.toString()) !== -1) {
let i = regexKeys.indexOf(path.toString())
this.routeStubs.regex[priority][i] = {
regex: path,
stub: newStub
}
debugSetup(`Regex stub replaced: ${path}`)
return newStub
}
this.routeStubs.regex[priority].push({
regex: path,
stub: newStub
})
debugSetup(`Regex stub added: ${path}`)
return newStub
}
debugSetupError('Only strings and regexs allowed')
throw new Error('Only regular expressions and strings allowed')
}
stub () {
return this.setStub.apply(this, arguments)
}
stubNotFound (response) {
let status = 500
let body = 'The requested route has not been declared.'
let contentType = 'text/plain'
debugResponeError('No Stub Found')
response.writeHead(status, { 'Content-Type': contentType })
response.end(body)
}
/**
* Restores all stubbed routes on the mock api server.
*/
restore () {
this.routeStubs = {
'text': {},
'regex': []
}
}
}