forked from WNC201703/online-academy-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
62 lines (52 loc) · 1.65 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 morgan = require('morgan');
const cors = require('cors')
const mongoose = require('mongoose');
const httpStatus=require('http-status');
const ApiError=require('./utils/ApiError')
const app = express();
app.use(express.static('public'));
app.use(cors());
app.use(express.json());
app.use(morgan('dev'));
require('./middlewares/routes.mdw')(app);
app.get('/err', function (req, res) {
throw new ApiError(httpStatus.NOT_FOUND,'Error!');
})
app.get('/api/ping', function (req, res, next){
return res.status(httpStatus.OK).json({
message:'Successful'
});
});
app.use(function (req, res, next) {
res.status(httpStatus.NOT_FOUND).json({
message: 'RESOURCE NOT FOOUND'
});
});
app.use(function (err, req, res, next) {
if (err instanceof ApiError) {
let statusCode = err.statusCode || httpStatus.INTERNAL_SERVER_ERROR;
let message = err.message || 'SOMETHING BROKEN';
return res.status(statusCode).json({
error_message:message
});
}
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
error_message: err.message || 'SOMETHING BROKEN'
});
})
const uri = `mongodb+srv://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@cluster0.fezar.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`;
mongoose
.connect(
uri,
{ useNewUrlParser: true, useUnifiedTopology: true }
)
.then(() => {
console.log('Connect Mongodb Successfully');
})
.catch((error) => console.log(error));
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server is running on PORT ${PORT}`);
});