-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
67 lines (54 loc) · 1.49 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
const express = require('express');
const cors = require('cors');
require('dotenv').config();
const swaggerUi = require('swagger-ui-express')
const booksRouter = require('./routes/books');
const genresRouter = require('./routes/genre');
const publisherRouter = require('./routes/publisher');
const authorRouter = require('./routes/author');
const swaggerFile = require('./swagger_output.json')
const app = express();
app.use(cors());
app.use(express.json());
app.get('/', (req, res) => {
res.json({
message: 'HELLO WORLD :)',
})
});
app.use('/api/v1/books', booksRouter);
app.use('/api/v1/genres', genresRouter);
app.use('/api/v1/publishers', publisherRouter);
app.use('/api/v1/authors', authorRouter);
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerFile));
app.use(notFound);
app.use(errorHandler);
function notFound(req, res, next) {
res.status(404);
const error = new Error(`🔍 - Not Found - ${req.originalUrl}`);
next(error);
}
/* eslint-disable no-unused-vars */
function errorHandler(err, req, res, next) {
if (err.name === 'ValidationError') {
err.status = 400;
let errors = {};
err.inner.forEach((e) => {
errors = {
...errors,
[e.path]: e.message
};
});
err.validationErrors = errors;
}
if (err.status) {
res.status(err.status);
} else {
res.status(500);
}
res.json({
message: err.message,
error: err,
stack: process.env.NODE_ENV === 'production' ? '🥞' : err.stack
});
}
module.exports = app;