-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
83 lines (69 loc) · 1.96 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
79
80
81
82
83
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
//configure .env
require('dotenv').config();
//configure express
const app = express();
app.use(express.json());
//configure cors
app.use(cors());
const PORT = process.env.PORT || 3000;
const DB_URL = process.env.DB_URL;
//Defining the routes
userRoutes = require('./routes/user');
app.use('/user', userRoutes);
menuRoutes = require('./routes/menus');
app.use('/menu', menuRoutes);
//Defining error handler
app.use(function (err, req, res, next) {
switch (err.type) {
case 'user_not_found':
res.status(404).send({
instance: req.originalUrl,
title: `User not found`,
detail: 'The user was not found in the database',
});
break;
case 'menu_not_found':
res.status(404).send({
instance: req.originalUrl,
title: `Menu not found`,
detail: err.message
});
break;
case 'bad_menu':
res.status(400).send({
instance: req.originalUrl,
title: 'Invalid Menu parameters',
detail: err.message,
});
break
case "menu_not_allowed":
res.status(403).send({
instance: req.originalUrl,
title: "You are not authorized to edit this menu",
});
break;
default:
console.log(err);
res.status(500).send({
instance: req.originalUrl,
title: 'Server Error',
detail: err.message,
});
}
});
//Establishing the database connection.
mongoose
.connect(DB_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.catch((error) => console.log('Database connection error' + error));
//Validating database connection
var connection = mongoose.connection;
connection.once('open', () => {
console.log(`database connected successfully! ${connection.db.databaseName}`);
});
//Express server.
app.listen(PORT, () => {
console.log(`Server started. Listening on port ${app.path() + ':' + PORT}`);
});