-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
78 lines (63 loc) · 2.24 KB
/
server.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
var collect = require('collect-stream')
, filter = require('object-filter')
, flat = require('flat')
, isFunction = require('core-util-is').isFunction
, isObject = require('core-util-is').isObject
, serializeError = require('serialize-error')
, slice = Array.prototype.slice
, endWithJson = function (statusCode, json, res, encoding) {
var payload = new Buffer(encoding.stringify(json))
res.setHeader('content-type', 'application/json')
res.setHeader('content-length', payload.length)
res.writeHead(statusCode)
res.end(payload)
}
, error = function (encoding, err, res) {
endWithJson(500, [ serializeError(err)], res, encoding)
}
, parseResponse = function (encoding, stream, callback) {
collect(stream, function (err, buffer) {
if (err) return callback(err)
try {
callback(null, encoding.parse(buffer.toString()))
} catch (err) {
callback(err)
}
})
}
, setupServer = function (options) {
var encoding = options.encoding || JSON
, url = options.url
, flatten = filter(flat(options.methods), isFunction)
, handler = function (req, res) {
if (req.url.slice(0, url.length) !== url) return
var methodName = req.url.replace(url, '').replace(/^\//, '')
, fun = flatten[methodName]
if (!fun) {
error(encoding, new Error('No method ' + methodName), res)
return
}
parseResponse(encoding, req, function (err, input) {
if (err) {
error(encoding, err, res)
return
}
if (input.sync) {
fun.apply(null, input.args)
res.end()
} else {
input.args.push(function () {
var args = slice.call(arguments)
if (args[0]) {
args[0] = serializeError(args[0])
}
endWithJson(200, args, res, encoding)
})
fun.apply(null, input.args)
}
})
}
handler.methodNames = Object.keys(flatten)
return handler
}
module.exports = setupServer