-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·94 lines (58 loc) · 2.08 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
const express = require('express');
require('./env');
const port = process.env.PORT || 5000;
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const seedDB = require('./backend/SeedData/SeedData');
//Routes
const userRoutes = require('./backend/routes/auth');
const productRoutes = require('./backend/routes/products');
const app = express();
const server = require("http").Server(app);
const io = require("socket.io")(server);
//Connect to database
//Connect to a database
const url = process.env.DATABASEURL || "mongodb://localhost/online-market";
mongoose.connect(url,{ useNewUrlParser: true,useCreateIndex: true, });
seedDB();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
io.sockets.on("connection",userSocket=>{
console.log("connected"+userSocket.id);
userSocket.on('myRoom',function(userRoom){
userSocket.join(userRoom.message);
})
userSocket.on('createdUser',(message)=>{
io.sockets.emit("updatedUsers",{update:true})
});
userSocket.on('createdProduct',(message)=>{
io.sockets.emit("updateProduct",{update:true,product:message.product})
});
userSocket.on('removedProduct',(message)=>{
io.sockets.emit('removeProduct',{update:true})
})
userSocket.on('disconnect', (reason)=> {
console.log('Client disconnected: - '+userSocket.id);
});
});
// Make io accessible to our router
app.use(function(req,res,next){
req.io = io;
next();
});
//Use Routes
app.use("/user",userRoutes);
app.use("/products",productRoutes);
app.use('/allUsers',express.static('allUsers'));
app.use('/allProducts',express.static('allProducts'));
//Io Connections
if (process.env.NODE_ENV === 'production') {
// Serve any static files
app.use(express.static(path.join(__dirname, 'client/build')));
// Handle React routing, return all requests to React app
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
server.listen(port, () => console.log(`Listening on port ${port}`));