-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
78 lines (63 loc) · 2.19 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
const express = require('express');
const app = express();
const {
metacall_inspect,
} = require('metacall');
const fs = require('fs');
const path = require('path');
// Initialize scripts from file
const load = new Promise((resolve, reject) => {
const scriptsPath = path.join(__dirname, 'scripts');
fs.readdir(scriptsPath, (err, files) => {
if (err) {
reject(err);
}
// All functions will be stored here
let functions = {};
files.forEach(file => {
try {
// This imports the scripts (Python, Ruby, C#...)
const absolute = path.join(scriptsPath, file);
if (!fs.lstatSync(absolute).isDirectory()) {
console.log('Loading...', file);
const handle = require(absolute);
functions = { ...functions, ...handle };
}
} catch (ex) {
reject(ex);
}
});
resolve(functions);
});
});
// Start the server
const start = (functions) => {
app.use(express.json());
app.get('/inspect', (req, res) => {
res.send(metacall_inspect());
});
app.post('/call/:name', (req, res) => {
if (!req.params.name) {
return res.status(400).send('A function name is required in the path; i.e: /call/sum.');
}
if (!Array.isArray(req.body)) {
return res.status(401).send('Invalid function parameters, the request body must be an array; i.e [3, 5].');
}
if (!(req.params.name && functions[req.params.name])) {
return res.status(404).send(`Function ${req.params.name} not found.`);
}
res.send(JSON.stringify(functions[req.params.name](...req.body)));
});
return app.listen(3051, () => {
console.log('Server listening...');
});
};
module.exports = (() => {
let server = null;
// Load scripts and start the server
load.then((functions) => { server = start(functions); }).catch(console.error);
// Export a close function to gracefully exit from the server
return {
close: () => { console.log('Closing server...'); server && server.close(); },
};
})();