-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
executable file
·79 lines (64 loc) · 1.92 KB
/
app.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
#!/usr/bin/env node
/**
* @file app.js
*
* Express server entry point.
*
* @author Will Pringle <[email protected]>
* @date November 2023
*/
'use strict';
const express = require('express');
const path = require('path');
const http = require('http');
const cors = require('cors');
const dcpInit = require('./src/dcp/init').init;
function setUpExpressServer()
{
const routes = require('./src/main').router;
const app = express();
const OpenApiValidator = require('express-openapi-validator');
app.use(express.json());
app.use(express.text());
app.use(express.urlencoded({ extended: false }));
// server openAPI spec at /spec and use it to validate requests
const spec = path.join(__dirname, 'spec.yaml');
app.use(cors());
// routes
app.use(express.static('public'));
app.use('/api/v0/', routes);
app.use('/spec', express.static(spec));
app.use(
OpenApiValidator.middleware({
apiSpec: './spec.yaml',
validateResponses: true, // <-- to validate responses
}),
);
// Error handling middleware for validation errors
app.use((err, req, res, next) => {
// If it's an OpenAPI error, format it nicely
if (err.status === 400 && err.type === 'request.openapi.validation')
{
return res.status(err.status).json({
error: 'Bad Request',
messages: err.errors.map(error => error.message),
});
}
// Pass on to default error handler or other error middleware
next(err);
});
// errors
app.use((err, req, res, next) => {
const status = err.status || 500;
console.error(err); // Dump error to console for debug
if (err.customMessage)
res.status(status).send({ message: err.customMessage });
res.status(status).send({ message: 'Internal Server Error' });
});
return app;
}
dcpInit().then(() => {
console.log('api @ http://localhost:1234');
const app = setUpExpressServer();
http.createServer(app).listen(1234);
});