forked from namshi/mockserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmockserver.js
More file actions
203 lines (173 loc) · 5.28 KB
/
mockserver.js
File metadata and controls
203 lines (173 loc) · 5.28 KB
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
var fs = require('fs');
var join = require('path').join;
var Combinatorics = require('js-combinatorics');
var normalizeHeader = require('header-case-normalizer');
/**
* 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: normalizeHeader(header[0]), value: header[1]};
};
/**
* Prepares headers to watch, no duplicates, non-blanks.
* Priority exports over ENV definition.
*/
var prepareWatchedHeaders = function () {
var exportHeaders = module.exports.headers && module.exports.headers.toString();
var headers = (exportHeaders || process.env.MOCK_HEADERS || '').split(',');
return headers.filter(function(item, pos, self) {
return item && self.indexOf(item) == pos;
});
}
/**
* 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};
};
/**
* 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) {
var mockName = prefix + (getBodyOrQueryString(body, query) || '') + '.mock';
var mockFile = join(mockserver.directory, path, mockName);
var content;
try {
content = fs.readFileSync(mockFile, {encoding: 'utf8'});
if (mockserver.verbose) {
console.log('Reading from '+ mockFile.yellow +' file: ' + 'Matched'.green);
}
} catch(err) {
if (mockserver.verbose) {
console.log('Reading from '+ mockFile.yellow +' file: ' + 'Not matched'.red);
}
content = (body || query) && getMockedContent(path, prefix);
}
return content;
}
var mockserver = {
directory: '.',
verbose: false,
headers: [],
init: function(directory, verbose) {
this.directory = directory;
this.verbose = !!verbose;
this.headers = prepareWatchedHeaders();
},
handle: function(req, res) {
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);
}
if(req.headers && mockserver.headers.length) {
mockserver.headers.forEach(function(header) {
header = header.toLowerCase();
if(req.headers[header]) {
headers.push('_' + normalizeHeader(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,
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) || content;
}
if(content) {
var mock = parse(content);
res.writeHead(mock.status, mock.headers);
return res.end(mock.body);
} else {
res.writeHead(404);
res.end('Not Mocked');
}
});
}
};
module.exports = function(directory, silent) {
mockserver.init(directory, silent);
return mockserver.handle;
};
module.exports.headers = null;