-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
74 lines (64 loc) · 2.15 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
'use strict';
require('dotenv').config();
const cors = require('cors');
const connect = require('./src/db');
const express = require('express');
const fs = require('fs');
const studio = require('@mongoosejs/studio/express');
const app = express();
const netlifyFunctions = fs.readdirSync('./netlify/functions').reduce((obj, path) => {
obj[path.replace(/\.js$/, '')] = require(`./netlify/functions/${path}`);
return obj;
}, {});
const topLevelFiles = new Set(
fs.readdirSync('./public').filter(file => file.endsWith('.html'))
);
app.use('/.netlify/functions', cors(), 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 data = { message: result.body };
try {
data = JSON.parse(result.body);
} catch (err) {}
return res.status(400).json(data);
}
res.json(JSON.parse(result.body))
}).
catch(err => {
res.status(500).json({ message: err.message, stack: err.stack, extra: err.extra });
});
});
app.use(
function rewriteUrlForTopLevelFiles(req, res, next) {
// `extensions: ['html']` mostly works, but doesn't handle the
// case where there is a directory with the same name as the HTML file.
// For example, there is both `public/affiliate.html` file and
// `public/affiliate` directory. Static middleware will go for the
// directory first. This middleware prevents that.
if (topLevelFiles.has(req.url.replace(/^\//, '') + '.html')) {
req.url = req.url + '.html';
}
next();
},
express.static(
'./public',
{ extensions: ['html'], etag: false, redirect: false }
)
);
(async function () {
const db = await connect();
app.use('/studio', studio('/studio/api', db));
app.listen(8888);
console.log('Listening on port 8888');
})();