forked from hugojosefson/getsandbox-express
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsandbox.js
67 lines (58 loc) · 1.9 KB
/
sandbox.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
var path = require('path');
var fs = require('fs');
var vm = require('vm');
var requireLike = require('require-like');
var morgan = require('morgan');
var attachLiquidTemplateEngine = require('./attach-liquid-template-engine');
var bodyParser = require('body-parser');
var app;
var Sandbox = {};
var warnedAboutMethods = {};
Sandbox.define = function define() {
var url, verb, handler;
if (arguments.length === 2) {
url = arguments[0];
verb = 'get';
handler = arguments[1];
} else if (arguments.length === 3) {
url = arguments[0];
verb = arguments[1];
handler = arguments[2];
}
verb = verb.toLowerCase();
url = url.replace(/{(.+?)}/g, ":$1");
url = encodeURI(url);
if (typeof app[verb] === 'function') {
app[verb](url, handler);
} else {
if (!warnedAboutMethods[verb]) {
console.warn("Ignoring registration of '" + verb.toUpperCase() + "' http method, because it's not implemented in Express.js.");
warnedAboutMethods[verb] = true;
}
}
};
var loadSandbox = function loadSandbox(expressApp, sandboxMainPath) {
if (!path.isAbsolute(sandboxMainPath)) {
throw new Error('sandbox main path must be absolute path');
}
app = expressApp;
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var sandboxDir = path.dirname(sandboxMainPath);
attachLiquidTemplateEngine(app, sandboxDir);
var sandbox = {};
sandbox.require = requireLike(sandboxMainPath);
sandbox.Sandbox = Sandbox;
sandbox.state = {};
sandbox.moment = require('moment-timezone');
sandbox._ = require('lodash');
sandbox.faker = require('faker');
sandbox.amanda = require('amanda');
sandbox.validator = require('validator');
var script = new vm.Script(fs.readFileSync(sandboxMainPath).toString(), {filename: sandboxMainPath});
script.runInNewContext(sandbox);
};
module.exports = {
loadSandbox: loadSandbox
};