blob: 2c7a373785d711c3661a214c6b0bb921014439c2 (
plain)
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
|
require('dotenv').config();
const path = require('path');
const chalk = require('chalk');
if (!process.env.MONGO_URL) {
throw new Error('No MONGO_URL set in .env!');
}
const db = require('monk')(process.env.MONGO_URL);
const express = require('express');
const app = express();
const requireFromString = require('require-from-string');
const models = require('./models')(db);
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/frontpage.html'));
});
app.all('/:path*', async (req, res) => {
const path = req.params.path.split('/')[0];
if (!path || path.length === 0) {
res.status(400);
res.send('Empty endpoint.');
}
const endpoint = await models.endpoints.findOne({name: path});
if (!endpoint) {
res.status(400);
res.send('No such endpoint.');
}
console.info(`${chalk.green(req.path)}, running endpoint "${chalk.yellow(endpoint.name)}".`);
const {code} = endpoint;
try {
const func = requireFromString(code);
func(req, res);
} catch (err) {
res.status(500);
console.error(chalk.red(`Error in endpoint ${endpoint.name}! Details below.`));
console.error(err);
res.send('Internal server error.');
}
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`${chalk.blue('faas')} listening on port ${port}! URL: ${chalk.yellow(`http://localhost:${port}`)}`));
|