-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunc.js
More file actions
46 lines (35 loc) · 1 KB
/
Copy pathFunc.js
File metadata and controls
46 lines (35 loc) · 1 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
'use strict';
var _ = require('lodash');
var Func = function Func(name, handler) {
this.name = name;
this.handler = handler;
if (!_.isString(this.name) || !this.name.length) {
throw new Error('"' + this.name + '" is not a valid function name');
}
if (!_.isFunction(this.handler)) {
throw new Error('Function handlers must be functions');
}
};
Func.prototype.processResponse = function processResponse(cb) {
return function(err, output) {
if (err) return cb(err);
if (!output) {
return cb(new Error('Function failed to provide valid output. Provided: "' + output + '"'));
}
if (_.isObject(output)) {
try {
output = JSON.stringify(output);
} catch(err) {
return cb(err);
}
}
if (typeof output !== 'string') {
output = output.toString();
}
cb(null, output);
};
};
Func.prototype.call = function call(context, data, cb) {
return this.handler.call(context, data, this.processResponse(cb));
};
module.exports = Func;