Agent Host changes for agents/nodejs-express-rest-api-orm-swagger
This commit is contained in:
+35
@@ -0,0 +1,35 @@
|
||||
require('dotenv').config();
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const express = require('express');
|
||||
const swaggerUi = require('swagger-ui-express');
|
||||
const YAML = require('yamljs');
|
||||
const apiRouter = require('./routes/api');
|
||||
|
||||
const app = express();
|
||||
const openApiPath = path.resolve(__dirname, '../webroot/openapi.yaml');
|
||||
const openApiDocument = YAML.parse(fs.readFileSync(openApiPath, 'utf8'));
|
||||
|
||||
app.disable('x-powered-by');
|
||||
app.use(express.json({ limit: '1mb' }));
|
||||
app.get('/openapi.yaml', (req, res) => res.sendFile(openApiPath));
|
||||
app.use('/docs', swaggerUi.serve, swaggerUi.setup(openApiDocument));
|
||||
app.get('/', (req, res) => res.redirect('/docs'));
|
||||
app.use('/api', apiRouter);
|
||||
|
||||
app.use((req, res) => res.status(404).json({
|
||||
success: false,
|
||||
error: { code: 404, message: 'Not found.' },
|
||||
}));
|
||||
|
||||
app.use((error, req, res, next) => {
|
||||
if (res.headersSent) return next(error);
|
||||
if (error instanceof SyntaxError && error.status === 400 && 'body' in error) {
|
||||
return res.status(400).json({ success: false, error: { code: 400, message: 'Invalid JSON body.' } });
|
||||
}
|
||||
console.error(error);
|
||||
return res.status(500).json({ success: false, error: { code: 500, message: 'Internal server error.' } });
|
||||
});
|
||||
|
||||
module.exports = app;
|
||||
Reference in New Issue
Block a user