-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
53 lines (43 loc) · 1.46 KB
/
client.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
var unflatten = require('flat').unflatten
, makeError = function (obj) {
var err = new Error(obj.message)
Object.keys(obj).forEach(function (key) {
err[key] = obj[key]
})
return err
}
, setupClient = function (request) {
return function (options) {
var remote = {}
, encoding = options.encoding || JSON
options.methodNames.forEach(function (name) {
remote[name] = function () {
var args = Array.prototype.slice.call(arguments)
, sync = typeof(args[args.length - 1]) !== 'function'
, callback = sync ? undefined : args.pop()
request({
url: options.url + '/' + name
, method: 'POST'
, body: encoding.stringify({ args: args, sync: sync })
, timeout: options.timeout || 30 * 1000
}, function (err, resp, body) {
var args;
if (sync) return
if (err) return callback(err)
try {
args = encoding.parse(body)
if (args[0]) args[0] = makeError(args[0])
} catch (err) {
err.type = 'ParseError'
err.source = body
return callback(err)
}
callback.apply(null, args)
}
)
}
})
return unflatten(remote)
}
}
module.exports = setupClient