-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
96 lines (73 loc) · 2.38 KB
/
Copy pathserver.js
File metadata and controls
96 lines (73 loc) · 2.38 KB
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
96
const express=require('express');
const dotenv=require('dotenv');
const logger=require('morgan');
const sequelize=require('./config/db');
const error=require('./middlewares/error');
const cookieparser=require('cookie-parser');
const cors=require('cors')
const bodyParser=require('body-parser');
//schema initialize
const User = require('./schemas/User');
const Muncipality = require('./schemas/Muncipality');
const Price = require('./schemas/Price');
const Billing = require('./schemas/Billing');
//initialize express app
const app=express();
//loads all env variables
dotenv.config({path:"./config/config.env"});
//Body parsing
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//connecting to database
const connectDb=async()=>{
try {
await sequelize.authenticate();
console.log('Connected to database successfully');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
connectDb()
//syncing models sequelize
const syncModel=async()=>{
try{
await User.sync();
await Price.sync();
await Muncipality.sync();
await Billing.sync();
console.log('Successfully synced all models');
}catch(err){
console.error('Failed in syncing models',err)
}
}
syncModel()
//CORS middleware
/*var corsMiddleware = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'localhost'); //replace localhost with actual host
res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, PATCH, POST, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization');
next();
}*/
//Initialize routes
const auth=require("./routes/auth");
const muncipality=require("./routes/muncipality");
//use cors
app.use(cors());
//routes
app.use("/api/user",auth);
app.use("/api/munci",muncipality);
//Initialize morgan
app.use(logger("dev"));
//cookie parser
app.use(cookieparser())
//Error Handler
app.use(error);
const PORT=process.env.PORT || 5000
const server=app.listen(PORT,()=>console.log(`Server running in ${process.env.NODE_ENV} mode on PORT ${PORT}`))
//Handling unhandled promise rejections
process.on('SequelizeAccessDeniedError', (error, promise) => {
console.log(`Error:${error.message}`);
//Close the server and exit process
server.close(() => process.exit(1));
})