generated from yandex-praktikum/express-mesto-gha
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
61 lines (50 loc) · 1.33 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
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const { errors } = require('celebrate');
const { routes } = require('./src/routes/index');
const { requestLogger, errorLogger } = require('./src/middlewares/logger');
const { INTERNAL_SERVER_ERROR } = require('./src/utils/constants');
const { PORT = 3000 } = process.env;
const app = express();
app.use(express.json());
app.use((req, res, next) => {
console.log(`${req.method}: ${req.path} ${JSON.stringify(req.body)}`);
next();
});
app.use(requestLogger);
app.use(cors());
app.use(routes);
function main() {
const url = 'mongodb://localhost:27017/mestodb';
try {
mongoose.connect(
url,
{
useNewUrlParser: true,
autoIndex: true,
},
(err) => {
if (err) throw err;
console.log('Connected to db');
}
);
} catch (err) {
throw new Error(err.message);
}
app.use(errorLogger);
app.use(errors());
app.use((err, req, res, next) => {
const { statusCode = INTERNAL_SERVER_ERROR, message } = err;
res.status(statusCode).send({
message:
statusCode === INTERNAL_SERVER_ERROR
? '500 Internal Server Error'
: message,
});
});
app.listen(PORT);
console.log(`Server listen on ${PORT}`);
}
main();