aboutsummaryrefslogtreecommitdiffstats
path: root/index.js
diff options
context:
space:
mode:
authorJan Tuomi <jan.tuomi@eficode.com>2018-07-12 12:22:15 +0300
committerJan Tuomi <jan.tuomi@eficode.com>2018-07-12 12:23:14 +0300
commit33fc72e5ce47a0669072d173e6f95e6e3661f516 (patch)
treea24c7ecf95a7ba54e6fa4d48e4727e74b358ea60 /index.js
parent2d9e63a11b1a0e6052d794d87b614df854ca4536 (diff)
Initial commit
Diffstat (limited to 'index.js')
-rw-r--r--index.js41
1 files changed, 41 insertions, 0 deletions
diff --git a/index.js b/index.js
new file mode 100644
index 0000000..8d5123d
--- /dev/null
+++ b/index.js
@@ -0,0 +1,41 @@
+require('dotenv').config();
+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 models = require('./models')(db);
+const express = require('express');
+const app = express();
+const requireFromString = require('require-from-string');
+
+app.all('*', async (req, res) => {
+ const path = req.path.split('/')[1];
+ 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.code;
+ try {
+ const func = requireFromString(code);
+ const output = 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}`)}`));