-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathcanned.js
339 lines (291 loc) · 9.36 KB
/
canned.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
"use strict";
var url = require('url')
var fs = require('fs')
var path = require('path')
var util = require('util')
var Response = require('./lib/response')
var querystring = require('querystring')
var url = require('url')
var cannedUtils = require('./lib/utils')
function Canned(dir, options) {
this.logger = options.logger
this.response_opts = {
cors_enabled: options.cors,
cors_headers: options.cors_headers
}
this.dir = process.cwd() + '/' + dir
}
function matchFile(matchString, fname, method) {
return matchString.match(
new RegExp(fname + '\\.' + method + '\\.(.+)')
)
}
function matchFileWithQuery(matchString) {
return matchString.match(/(.*)\?(.*)\.(.*)\.(.*)/)
}
function matchFileWithExactQuery(matchString, fname, queryString, method) {
var escapedQueryString = cannedUtils.escapeRegexSpecialChars(queryString)
return matchString.match(
new RegExp(fname +
"(?=.*" +
escapedQueryString.split("&").join(")(?=.*") +
").+" +
method)
)
}
function getFileFromRequest(httpObj, files) {
if (!files) return false
var m, i, e, matchString, matchPattern, fileMatch
// if query params, match regexp based on fname to request
if(httpObj.query)
{
for (i = 0, e = files[i]; e != null; e = files[++i]) {
fileMatch = matchFileWithQuery(e)
if (fileMatch)
{
matchString = httpObj.fname + "?" + httpObj.query + "." + httpObj.method
m = matchFileWithExactQuery(matchString, fileMatch[1], fileMatch[2], fileMatch[3])
if (m) return { fname: e, mimetype: fileMatch[4] }
}
}
}
// if match regexp based on request to fname
for (i = 0, e = files[i]; e != null; e = files[++i]) {
m = matchFile(e, httpObj.fname, httpObj.method)
if (m) return { fname : m[0], mimetype : m[1] }
}
return false
}
function getContentType(mimetype){
return Response.content_types[mimetype]
}
// replace any body comments in format //! [string]
function stripBodyComments(data) {
return data && data.replace(/\/\/\! [\w]*: ([\w {}":,@./]*)/, '').trim()
}
function getSelectedResponse(responses, content, headers) {
var selectedResponse = responses[0]
if(!(content || headers)) return selectedResponse // noting to select on
// find request matches and assign to chosenResponse
responses.forEach(function(response) {
var regex = new RegExp(/\/\/\! [A-z]*: ([\w {}":,@.]*)/g)
var request = JSON.parse(regex.exec(response)[1])
var variation = cannedUtils.extend({}, content, headers)
if(typeof request !== 'object') return; // nothing to match on
Object.keys(request).forEach(function(key) {
if(request[key] === variation[key]) {
selectedResponse = response
}
})
})
return selectedResponse
}
// return multiple response bodies as array
Canned.prototype.getEachResponse = function(data) {
data = cannedUtils.removeJSLikeComments(data)
var responses = data.split(/\n(?=[\/\/!])/).filter(function (e) { return e !== '' })
return responses
}
Canned.prototype.getVariableResponse = function(data, content, headers) {
// return sanatized data if no conditional body comments
if(!data.match(/\/\/\! [\w]*: {.*}/)) {
return JSON.stringify(stripBodyComments(data))
}
var responses = this.getEachResponse(data)
var selectedResponse = stripBodyComments(getSelectedResponse(responses, content, headers))
return JSON.stringify(selectedResponse)
}
Canned.prototype._extractOptions = function (data, httpObj) {
var lines = data.split('\n')
var opts = {}
if (lines[0].indexOf('//! status') !== -1) {
try {
var content = lines[0].replace('//!', '')
content = content.split(',').map(function (s) {
var parts = s.split(':');
parts[0] = '"' + parts[0].trim() + '"'
return parts.join(':')
}).join(',')
opts = JSON.parse('{' + content + '}')
} catch (e) {
this._log('Invalid file header format try //! statusCode: 201')
opts = {}
}
lines.splice(0, 1)
}
var defaultStatusCode
if (lines.length === 0 || lines[0].length === 0) {
defaultStatusCode = 204
} else {
defaultStatusCode = 200
}
opts.statusCode = opts.statusCode || defaultStatusCode
opts.data = JSON.parse(this.getVariableResponse(data, httpObj.content, httpObj.headers));
return opts
}
Canned.prototype.sanatizeContent = function (data, fileObject) {
var sanatized
if (data.length === 0) {
return data
}
switch (fileObject.mimetype) {
case 'json':
// make sure we return valid JSON even so we support comments
try {
sanatized = JSON.stringify(JSON.parse(cannedUtils.removeJSLikeComments(data)))
} catch (err) {
this._log("problem sanatizing content for " + fileObject.fname + " " + err)
return false
}
break
default:
sanatized = data
}
return sanatized
}
Canned.prototype._responseForFile = function (httpObj, files, cb) {
var that = this
var fileObject = getFileFromRequest(httpObj, files)
httpObj.filename = fileObject.fname
if (fileObject) {
var filePath = httpObj.path + '/' + fileObject.fname
fs.readFile(filePath, { encoding: 'utf8' }, function (err, data) {
var response
if (err) {
response = new Response(getContentType('html'), '', 404, httpObj.res, that.response_opts)
cb('Not found', response)
} else {
var _data = that._extractOptions(data, httpObj)
data = _data.data
var statusCode = _data.statusCode
var content = that.sanatizeContent(data, fileObject)
if (content !== false) {
response = new Response(_data.contentType || getContentType(fileObject.mimetype), content, statusCode, httpObj.res, that.response_opts)
cb(null, response)
} else {
content = 'Internal Server error invalid input file'
response = new Response(getContentType('html'), content, 500, httpObj.res, that.response_opts)
cb(null, response)
}
}
})
} else {
var response = new Response(getContentType('html'), '', 404, httpObj.res, that.response_opts)
cb('Not found', response)
}
}
Canned.prototype._log = function (message) {
if (this.logger) this.logger.write(message)
}
Canned.prototype._logHTTPObject = function (httpObj) {
this._log(' served via: .' + httpObj.pathname.join('/') + '/' + httpObj.filename + '\n')
}
Canned.prototype.respondWithDir = function (httpObj) {
var that = this;
var fpath = httpObj.path + '/' + httpObj.dname
fs.readdir(fpath, function (err, files) {
httpObj.fname = 'index'
httpObj.path = fpath
that._responseForFile(httpObj, files, function (err, resp) {
if (err) {
that._log(' not found\n')
} else {
that._logHTTPObject(httpObj)
}
resp.send()
})
})
}
Canned.prototype.respondWithAny = function (httpObj, files) {
var that = this;
httpObj.fname = 'any';
that._responseForFile(httpObj, files, function (err, resp) {
if (err) {
that._log(' not found\n')
} else {
that._logHTTPObject(httpObj)
}
resp.send()
})
}
Canned.prototype.responder = function(body, req, res) {
var httpObj = {}
var that = this
var parsedurl = url.parse(req.url)
httpObj.headers = req.headers
httpObj.content = body
httpObj.pathname = parsedurl.pathname.split('/')
httpObj.dname = httpObj.pathname.pop()
httpObj.fname = '_' + httpObj.dname
httpObj.path = this.dir + httpObj.pathname.join('/')
httpObj.query = parsedurl.query
httpObj.method = req.method.toLowerCase()
httpObj.res = res
this._log('request: ' + httpObj.method + ' ' + req.url)
if (httpObj.method === 'options') {
that._log('Options request, serving CORS Headers\n')
var response = new Response(null, '', 200, res, this.response_opts)
return response.send()
}
fs.readdir(httpObj.path, function (err, files) {
fs.stat(httpObj.path + '/' + httpObj.dname, function (err, stats) {
if (err) {
that._responseForFile(httpObj, files, function (err, resp) {
if (err) {
that.respondWithAny(httpObj, files);
} else {
that._logHTTPObject(httpObj)
resp.send()
}
})
} else {
if (stats.isDirectory()) {
that.respondWithDir(httpObj);
} else {
new Response('html', '', 500, httpObj.res).send();
}
}
})
})
}
Canned.prototype.responseFilter = function (req, res) {
var that = this
var body = ''
// assemble response body if GET/POST/PUT
switch(req.method) {
case 'PUT':
case 'POST':
req.on('data', function (data) {
body += data
})
req.on('end', function () {
var responderBody = querystring.parse(body);
if (req.headers && req.headers['content-type'] === 'application/json') {
try {
responderBody = JSON.parse(body)
} catch (e) {
that._log('Invalid json content')
}
}
that.responder(responderBody, req, res)
})
break
case 'GET':
var query = url.parse(req.url).query
if (query && query.length > 0) {
body = querystring.parse(query)
}
that.responder(body, req, res)
break
default:
that.responder(body, req, res)
break
}
}
var canned = function (dir, options) {
if (!options) options = {}
dir = path.relative(process.cwd(), dir)
var c = new Canned(dir, options)
return c.responseFilter.bind(c)
}
module.exports = canned