forked from goitacademy/nodejs-homework-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
45 lines (35 loc) · 1016 Bytes
/
app.js
File metadata and controls
45 lines (35 loc) · 1016 Bytes
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
const express = require("express");
const logger = require("morgan");
const cors = require("cors");
const contactsRouter = require("./routes/api/contacts.js");
const usersRouter = require("./routes/api/users.js");
const app = express();
const formatsLogger = app.get("env") === "development" ? "dev" : "short";
app.use(logger(formatsLogger));
app.use(cors());
app.use(express.json());
// routes
app.use("/api/contacts", contactsRouter);
app.use("/api/users", usersRouter);
app.use(express.static("public"));
app.use((req, res) => {
res.status(404).json({ message: "Not found" });
});
// error handling
app.use((error, req, res, next) => {
// handle mongoose validation error
if (error.name === "ValidationError") {
return res.status(400).json({
message: error.message,
});
}
if (error.status) {
return res.status(error.status).json({
message: error.message,
});
}
return res.status(500).json({
message: "Internal server error",
});
});
module.exports = app;