This repository has been archived by the owner on Aug 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (47 loc) · 1.68 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
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json({ strict: true }));
app.use(cors());
app.options('*', cors()); //change to domain in production
app.enable('trust proxy');
var endpoints = {}
fs.readdirSync('./endpoints/').forEach(function (file) {
let m = require('./endpoints/' + file);
if (m.name == null || m.execute == null || m.verify == null || m.method == null) {
console.error(`\x1b[31mInvalid endpoint: ${file}\x1b[0m`);
}
else if (m.name in endpoints) {
console.error(`\x1b[31mDuplicate endpoint name: ${file} (${m.name})\x1b[0m`);
}
else {
endpoints[m.name] = m;
console.log(`Loaded endpoint: ${file} (${m.name})`);
}
});
app.use('/', function (req, res) {
const endpoint = req.url.split('?')[0].slice(1);
if (!endpoints[endpoint]) {
res.status(404).json({ status: 404, error: 'Could not find endpoint' });
}
else if (endpoints[endpoint].method !== req.method) {
res.status(400).json({ status: 400, error: `Invalid method for endpoint. Must use ${endpoints[endpoint].method}` });
}
else if (endpoints[endpoint].verify(req, res)) {
try {
endpoints[endpoint].execute(req, res);
}
catch {
res.sendStatus(500).end({ status: 500, error: 'Internal server error' });
}
}
else {
res.status(403).json({ status: 403, error: 'Endpoint access denied. Do you have a valid authentication header?' });
}
})
const PORT = 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});