forked from namshi/mockserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mockserver.js
239 lines (202 loc) · 5.79 KB
/
mockserver.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
var fs = require('fs');
var join = require('path').join;
var colors = require('colors')
var Combinatorics = require('js-combinatorics').Combinatorics;
/**
* Returns the status code out of the
* first line of an HTTP response
* (ie. HTTP/1.1 200 Ok)
*/
var parseStatus = function (header) {
return header.split(' ')[1];
};
/**
* Parses an HTTP header, splitting
* by colon.
*/
var parseHeader = function (header) {
header = header.split(': ');
return { key: header[0], value: header[1] };
};
/**
* Parser the content of a mockfile
* returning an HTTP-ish object with
* status code, headers and body.
*/
var parse = function (content) {
var headers = {};
var body;
var bodyContent = [];
content = content.split('\n');
var status = parseStatus(content[0]);
var headerEnd = false;
delete content[0];
content.forEach(function (line) {
if (headerEnd) {
bodyContent.push(line);
} else if (line === '' || line === '\r') {
headerEnd = true;
} else {
var header = parseHeader(line);
headers[header.key] = header.value;
}
});
body = bodyContent.join('\n');
return { status: status, headers: headers, body: body };
};
/**
* Parser the content of a js file
* returning an HTTP-ish object with
* status code, headers and body.
*/
var parseJS = function (content) {
var headers = {};
var body;
content.headers.forEach(function (headerItem) {
var header = parseHeader(headerItem);
headers[header.key] = header.value;
})
if (typeof content.body === 'object') {
body = JSON.stringify(content.body);
} else {
body = content.body;
}
if (typeof content.status === 'number') {
status = content.status;
} else {
status = parseStatus(content.status);
}
return { status: status, headers: headers, body: body };
};
/**
* Returns the body or query string to be used in
* the mock name.
*
* In any case we will prepend the value with a double
* dash so that the mock files will look like:
*
* POST--My-Body=123.mock
*
* or
*
* GET--query=string&hello=hella.mock
*/
function getBodyOrQueryString(body, query) {
if (query) {
return '--' + query;
}
if (body && body !== '') {
return '--' + body;
}
return body;
}
/**
* Ghetto way to get the body
* out of the request.
*
* There are definitely better
* ways to do this (ie. npm/body
* or npm/body-parser) but for
* the time being this does it's work
* (ie. we don't need to support
* fancy body parsing in mockserver
* for now).
*/
function getBody(req, callback) {
var body = '';
req.on('data', function (b) {
body = body + b.toString();
});
req.on('end', function () {
callback(body);
});
}
function getMockedContent({ path, prefix, body, query, directory }) {
var mockedJSName = prefix + (getBodyOrQueryString(body, query) || '') + '.js';
var mockJSFile = join(directory, path, mockedJSName);
try {
var foundFile = require(process.cwd() + '/' + mockJSFile);
mockserver.log('Serving mocks from... \n -> ' + mockJSFile, 'white')
foundFile.isJS = true;
return foundFile;
} catch (err) {
}
var mockedMockName = prefix + (getBodyOrQueryString(body, query) || '') + '.mock';
var mockMockFile = join(directory, path, mockedMockName);
try {
mockserver.log('Serving mocks from...\n -> ' + mockMockFile, 'white')
return fs.readFileSync(mockMockFile, { encoding: 'utf8' });
} catch (err) {
return (body || query) && getMockedContent({ path, prefix, directory });
}
}
var mockserver = {
directory: '.',
verbose: false,
log: function (msg, color) {
if (this.verbose) {
console.log('[ Mockserver ]: '[color] + msg)
}
},
use: function (name, value) {
if (value && name) {
this[name] = value
}
},
handle: function (req, res) {
res.setHeader('Access-Control-Allow-Origin', '*')
getBody(req, function (body) {
var url = req.url;
var path = url;
var queryIndex = url.indexOf('?'),
query = queryIndex >= 0 ? url.substring(queryIndex).replace(/\?/g, '') : '',
method = req.method.toUpperCase(),
headers = [];
if (queryIndex > 0) {
path = url.substring(0, queryIndex);
}
var watchedHeaders = module.exports.headers;
if (watchedHeaders && !Array.isArray(watchedHeaders)) {
watchedHeaders = [watchedHeaders];
}
if (req.headers && watchedHeaders && watchedHeaders.length) {
watchedHeaders.forEach(function (header) {
if (req.headers[header]) {
headers.push('_' + header + '=' + req.headers[header]);
}
});
}
// Now, permute the possible headers, and look for any matching files, prioritizing on
// both # of headers and the original header order
var content,
directory = mockserver.directory,
permutations = [[]];
if (headers.length) {
permutations = Combinatorics.permutationCombination(headers).toArray().sort(function (a, b) {
return b.length - a.length;
});
permutations.push([]);
}
while (permutations.length) {
var prefix = method + permutations.pop().join('');
content = getMockedContent({ path, prefix, body, query, directory }) || content;
}
if (content) {
mockserver.log('Mocks sent to client from...\n' + url, 'green')
var mock = content.isJS ? parseJS(content) : parse(content);
res.writeHead(mock.status, mock.headers);
return res.end(mock.body);
} else {
mockserver.log('No mocks matched from...\n -> ' + url, 'red')
res.writeHead(404);
res.end('Not Mocked');
}
});
}
};
module.exports = function (directory, verbose) {
mockserver.use('directory', directory);
mockserver.use('verbose', verbose);
return mockserver.handle;
};
module.exports.headers = [];