-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
95 lines (78 loc) · 2.39 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
/** Globals */
if (!global.JOI) {
global.JOI = require('joi');
}
if (!global.Response) {
global.Response = require('./utils/Response');
}
if (!global.STATUS_CODE) {
global.STATUS_CODE = require('./constants/status-codes');
}
if (!global.CUSTOM_MESSAGE) {
global.CUSTOM_MESSAGE = require('./constants/custom-messages');
}
if (!global.ENVCONFIG) {
global.ENVCONFIG = require("./config/dev.env");
}
/** Begin SEQUELIZE Connection */
global.Sequelize = require('sequelize');
Sequelize.Promise = global.Promise
global.sequelize = new Sequelize(ENVCONFIG.DB_DATABASE, ENVCONFIG.DB_USERNAME, ENVCONFIG.DB_PASSWORD, {
host: ENVCONFIG.DB_HOST,
port: ENVCONFIG.DB_PORT,
dialect: ENVCONFIG.DB_DIALECT,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
logging: console.log,
logging: function (str) {
console.log(str);
console.log(ENVCONFIG.DB_DATABASE)
}
});
/** Check if connection stablished */
sequelize.authenticate().then(() => {
console.log('Connection has been established successfully.');
}).catch(err => {
console.error('Unable to connect to the database:', err);
});
/** End SEQUELIZE Connection */
/** Routes */
const userRoutes = require("./routes/user");
const rolesRoutes = require("./routes/roles");
const activitiesRoutes = require("./routes/activities");
const authRoutes = require("./routes/auth");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
/** Handle Routes */
app.use("/user", userRoutes);
app.use("/roles", rolesRoutes);
app.use("/activities", activitiesRoutes);
app.use("/auth", authRoutes);
app.use((req, res, next) => {
const error = new Error('Route not found!');
error.status = 500;
next(error);
});
app.use((error, req, res, next) => {
return res.send(Response.sendResponse(false, "", error.message, error.status || 500));
});
module.exports = app;