2020-01-14 13:25:13 +01:00
|
|
|
import express from 'express';
|
2020-04-22 17:24:15 +02:00
|
|
|
import bodyParser from 'body-parser';
|
2020-01-14 13:25:13 +01:00
|
|
|
import swagger from 'swagger-ui-express';
|
2020-04-21 10:53:07 +02:00
|
|
|
import jsonRefParser, {JSONSchema} from '@apidevtools/json-schema-ref-parser';
|
2020-04-22 17:24:15 +02:00
|
|
|
import db from './db';
|
2020-01-14 13:25:13 +01:00
|
|
|
|
|
|
|
|
|
|
|
// tell if server is running in debug or production environment
|
2020-04-22 17:38:24 +02:00
|
|
|
console.log(process.env.NODE_ENV === 'production' ? '===== PRODUCTION =====' : process.env.NODE_ENV === 'test' ? '' :'===== DEVELOPMENT =====');
|
2020-01-14 13:25:13 +01:00
|
|
|
|
|
|
|
|
2020-04-22 17:24:15 +02:00
|
|
|
// mongodb connection
|
|
|
|
db.connect();
|
2020-04-20 16:17:43 +02:00
|
|
|
|
2020-01-14 13:25:13 +01:00
|
|
|
// create Express app
|
|
|
|
const app = express();
|
|
|
|
app.disable('x-powered-by');
|
|
|
|
|
|
|
|
// get port from environment, defaults to 3000
|
|
|
|
const port = process.env.PORT || 3000;
|
|
|
|
|
2020-04-22 17:24:15 +02:00
|
|
|
//middleware
|
|
|
|
app.use(express.json({ limit: '5mb'}));
|
|
|
|
app.use(express.urlencoded({ extended: false, limit: '5mb' }));
|
|
|
|
app.use(bodyParser.json());
|
|
|
|
app.use((err, req, res, ignore) => { // bodyParser error handling
|
|
|
|
res.status(400).send({status: 'Invalid JSON body'});
|
|
|
|
});
|
|
|
|
|
2020-01-14 13:25:13 +01:00
|
|
|
// require routes
|
|
|
|
app.use('/', require('./routes/root'));
|
2020-04-22 17:24:15 +02:00
|
|
|
app.use('/', require('./routes/user'));
|
2020-01-14 13:25:13 +01:00
|
|
|
|
|
|
|
// Swagger UI
|
2020-04-21 10:53:07 +02:00
|
|
|
let oasDoc: JSONSchema = {};
|
|
|
|
jsonRefParser.bundle('oas/oas.yaml', (err, doc) => {
|
|
|
|
if(err) throw err;
|
|
|
|
oasDoc = doc;
|
|
|
|
oasDoc.paths = oasDoc.paths.allOf.reduce((s, e) => Object.assign(s, e));
|
|
|
|
swagger.setup(oasDoc, {defaultModelsExpandDepth: -1, customCss: '.swagger-ui .topbar { display: none }'});
|
|
|
|
});
|
|
|
|
app.use('/api', swagger.serve, swagger.setup(oasDoc, {defaultModelsExpandDepth: -1, customCss: '.swagger-ui .topbar { display: none }'}));
|
2020-01-14 13:25:13 +01:00
|
|
|
|
2020-04-22 17:24:15 +02:00
|
|
|
app.use((req, res) => { // 404 error handling
|
|
|
|
res.status(404).json({status: 'Not found'});
|
|
|
|
});
|
|
|
|
|
|
|
|
app.use((err, req, res, ignore) => { // internal server error handling
|
|
|
|
console.error(err);
|
|
|
|
res.status(500).json({status: 'Internal server error'});
|
|
|
|
});
|
|
|
|
|
|
|
|
|
2020-01-14 13:25:13 +01:00
|
|
|
// hook up server to port
|
2020-04-22 17:24:15 +02:00
|
|
|
const server = app.listen(port, () => {
|
2020-04-22 17:38:24 +02:00
|
|
|
console.log(process.env.NODE_ENV === 'test' ? '' : `Listening on http://localhost:${port}`);
|
2020-01-14 13:25:13 +01:00
|
|
|
});
|
2020-04-22 17:24:15 +02:00
|
|
|
|
|
|
|
module.exports = server;
|