-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
99 lines (80 loc) · 2.33 KB
/
server.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
96
97
98
99
const express = require('express');
const cors = require('cors');
const path = require('path');
const db = require('./models');
const dbConfig = require('./config/db.config');
const socketIo = require('socket.io');
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
const Role = db.role;
const corsOptions = {
origin:
process.env.NODE_ENV !== `production`
? `http://localhost:3000`
: `https://simple-chat-devhectorga.herokuapp.com/`,
};
app.use(cors(corsOptions));
app.use(express.json({ extended: true }));
const rut = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.rttv4.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`;
db.mongoose
.connect(rut, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('Successfully connect to MongoDB.');
initial();
})
.catch((err) => {
console.error('Connection error', err);
process.exit();
});
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
app.get('/', (req, res) => {
res.json({ message: 'Welcome to Chat Application' });
});
require('./routes/auth.routes')(app);
require('./routes/user.routes')(app);
const expressServer = app.listen(port, (error) => {
if (error) throw error;
console.log('Server running on port ', port);
});
const io = socketIo(expressServer);
const Chat = require('./routes/chat.routes');
Chat(app, io);
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: 'user',
}).save((err) => {
if (err) {
console.log('error', err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: 'moderator',
}).save((err) => {
if (err) {
console.log('error', err);
}
console.log("added 'moderator' to roles collection");
});
new Role({
name: 'admin',
}).save((err) => {
if (err) {
console.log('error', err);
}
console.log("added 'admin' to roles collection");
});
}
});
}