-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
65 lines (50 loc) · 1.53 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
require("dotenv").config();
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");
const createError = require("http-errors");
const logger = require("morgan");
const express = require("express");
const cors = require("cors");
require("./config/db.config");
const app = express();
/* Middlewares */
app.use(express.json());
app.use(logger("dev"));
app.use(cors());
/* Routes */
const routes = require("./config/routes.config");
app.use("/api", routes);
/* Handle Errors */
app.use((req, res, next) => {
next(createError(404, "Route not found"));
});
app.use((error, req, res, next) => {
if (error instanceof mongoose.Error.ValidationError)
error = createError(400, error);
else if (error instanceof mongoose.Error.CastError)
error = createError(404, "Resource not found");
else if (error instanceof jwt.JsonWebTokenError)
error = createError(401, error);
else if (error.message.includes("E11000"))
error = createError(400, "Already exists");
else if (!error.status) error = createError(500, error);
if (error.status >= 500) {
console.error(error);
}
const data = {};
data.message = error.message;
data.errors = error.errors
? Object.keys(error.errors).reduce(
(errors, key) => ({
...errors,
[key]: error.errors[key].message || error.errors[key],
}),
{}
)
: undefined;
res.status(error.status).json(data);
});
const port = Number(process.env.PORT || 3001);
app.listen(port, () => {
console.log(`Ready! Listen on port ${port}`);
});