-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpress.js
More file actions
61 lines (49 loc) · 1.81 KB
/
Copy pathexpress.js
File metadata and controls
61 lines (49 loc) · 1.81 KB
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
const fs = require('fs-extra');
const path = require('path');
const child_process = require('child_process');
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const { promisify } = require('util');
const exec = promisify(child_process.exec);
const config = require('./config');
/**
* Starts the Express server that receives notifications
* @param {(notification: import('./config').PydtNotification) => Promise<void>} callback - Callback to handle incoming notifications
* @returns {Promise<void>}
*/
async function startExpressServer(callback) {
if (typeof callback !== 'function')
throw new Error('Callback is not a function');
/** @type {import('express').Application} */
const app = express();
app.use(morgan('combined'));
app.get('/', (req, res) => res.send('Up and running!'));
app.post('/', bodyParser.json({type: '*/*'}), (req, res) => {
console.log({ type: 'requestMatched', headers: req.headers, body: req.body });
Promise.resolve(callback(req.body))
.then(() => res.send())
.catch(e => {
console.error(e);
res.status(500).json(e);
});
});
const socket = config.http.socket
? path.resolve(config.http.socket)
: null;
if (socket) {
if (await fs.exists(socket)) {
await fs.unlink(socket);
}
}
await new Promise((resolve, reject) => {
const server = app.listen(config.http.socket || config.http.port, resolve);
server.on('error', reject);
});
if (socket) {
await exec(`chgrp www-data '${socket}'`);
await exec(`chmod 770 '${socket}'`);
}
console.log(`Listening on ${socket || config.http.port}`);
}
module.exports = { startExpressServer };