-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
78 lines (66 loc) · 2.1 KB
/
index.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
'use strict';
const assert = require('assert');
const express = require('express');
const fs = require('fs');
const mongoose = require('mongoose');
const path = require('path');
assert.ok(process.env.MONGODB_CONNECTION_STRING);
require('./build')(process.env.WATCH);
const app = express();
app.use(express.json());
const netlifyFunctions = fs.readdirSync('./netlify/functions').reduce((obj, path) => {
obj[path.replace(/\.js$/, '')] = require(`./netlify/functions/${path}`);
return obj;
}, {});
app.use('/.netlify/functions', express.json(), function netlifyFunctionsMiddleware(req, res) {
const actionName = req.path.replace(/^\//, '');
if (!netlifyFunctions.hasOwnProperty(actionName)) {
throw new Error(`Action ${actionName} not found`);
}
const action = netlifyFunctions[actionName];
const params = {
headers: req.headers,
body: JSON.stringify(req.body),
queryStringParameters: req.query
};
action.handler(params).
then(result => {
if (result.statusCode >= 400) {
let message = result.body;
try {
message = JSON.parse(message);
} catch (err) {}
return res.status(400).json(typeof message === 'string' ? { message } : message);
}
let isHtml = false;
if (result.headers) {
res.set(result.headers);
}
try {
result.body = JSON.parse(result.body);
isHtml = false;
} catch (err) {
isHtml = true;
}
if (isHtml) {
if (result.isBase64Encoded) {
result.body = Buffer.from(result.body, 'base64');
}
res.end(result.body);
} else {
res.json(result.body);
}
}).
catch(err => {
res.status(500).json({ message: err.message, stack: err.stack });
});
});
mongoose.connect(process.env.MONGODB_CONNECTION_STRING);
app.use('/studio', require('@mongoosejs/studio/express')('/studio/api'));
app.use(express.static('./public'));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './public/index.html'));
});
const port = process.env.PORT || 4488;
app.listen(port);
console.log('Listening on port', port);