-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
78 lines (63 loc) · 1.75 KB
/
index.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
68
69
70
71
72
73
74
75
76
77
78
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
/**
* Database connectivity
*/
const localurl = "mongodb://127.0.0.1/moscow"
mongoose
.connect(localurl, { useNewUrlParser: true }, (err, db) =>{
if(err){
console.log(err);
console.log("Database Connectivity Error!!");
} else {
console.log("Database Connectivity Successfull!");
}
})
mongoose.Promise = global.Promise;
/**
* Using MiddleWares
*/
app.use(morgan("dev"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// handling cors errors
app.use(cors());
/**
* Routes
*/
const rootRoutes = require('./routes/index.js');
app.use('/api', rootRoutes);
// Handling the errors
/**
* If none of the above middlewares are hit there is definately an error
*/
app.use((req, res, next) => {
// create a new error object(inbuilt)
const error = new Error("Not Found!!");
error.status = 404;
// call the universal error handler and pass it to the next middleware this error
// Till here it was sure that a wrong url has been hit.
next(error);
});
/**
* Handling universal errors like dberror or server error etc
* we'll have a error function from the previous middleware || from the universal error
* This route is bound to hit
*/
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
"error": {
"message": error.message
}
});
});
// get the port no.
const port = 5000 || process.env.PORT;
app.listen(port, "localhost", ()=>{
console.log("Server running at port " + port);
});