-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcode.js
More file actions
81 lines (77 loc) · 2.19 KB
/
Copy pathcode.js
File metadata and controls
81 lines (77 loc) · 2.19 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
// eslint-disable-next-line import/no-extraneous-dependencies
const _ = require('lodash');
const vm = require('vm');
const { messages } = require('elasticio-node');
const co = require('co');
const request = require('co-request');
function wait(timeout) {
return new Promise((ok) => {
setTimeout(() => {
this.logger.debug('Done wait');
ok();
}, timeout);
this.logger.debug('Start wait sec=%s', timeout);
});
}
// eslint-disable-next-line consistent-return,func-names
exports.process = async function (msg, conf, snapshot) {
const vmExports = {};
const ctx = vm.createContext({
// Node Globals
Buffer,
clearInterval,
clearTimeout,
console,
exports: vmExports,
global: {},
module: { exports: vmExports },
process,
require,
setInterval,
setTimeout,
URL,
URLSearchParams,
// Elasticio Specific Functionality
emitter: this,
messages,
msg,
// Other Libraries
_,
request,
wait: wait.bind(this),
});
this.logger.debug('Running the code %s', conf.code);
vm.runInContext(conf.code, ctx, {
displayErrors: true,
});
this.logger.debug("No result, let's check the run object if it was created?");
if (ctx.run && typeof ctx.run.apply === 'function') {
let result;
if (ctx.run.constructor.name === 'GeneratorFunction') {
this.logger.debug('Run variable is a generator');
const fn = co.wrap(ctx.run);
result = fn.apply(this, [msg, conf, snapshot]);
} else {
this.logger.debug('Run variable is a function, calling it');
result = ctx.run.apply(this, [msg, conf, snapshot]);
}
if (typeof result === 'object' && typeof result.then === 'function') {
this.logger.debug('Returned value is a promise, will evaluate it');
let returnResult;
try {
returnResult = await result;
this.logger.debug('Promise resolved');
if (returnResult) {
return messages.newMessageWithBody(returnResult);
}
this.emit('end');
} catch (e) {
this.logger.error('Promise failed', e);
throw e;
}
}
} else {
this.logger.debug("Run function was not found, it's over now");
this.emit('end');
}
};