-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
92 lines (78 loc) · 2.02 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
//importing
import express from "express";
import mongoose from "mongoose";
import Messages from "./dbMessages.js";
import Pusher from "pusher";
import cors from "cors";
//app config
const app = express();
const port = process.env.PORT || 9000;
const pusher = new Pusher({
appId: "1226908",
key: "7ee8a313177bb1eeff7e",
secret: "aac0f843f5f3f540e339",
cluster: "eu",
useTLS: true,
});
//middleware
app.use(express.json());
app.use(cors());
//DB config
const connection_url =
"mongodb+srv://admin:[email protected]/whatsappdb?retryWrites=true&w=majority";
mongoose.connect(connection_url, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.once("open", () => {
console.log("DB connected");
const msgCollection = db.collection("messagecontents");
const changeStream = msgCollection.watch();
changeStream.on("change", (change) => {
console.log(change);
if (change.operationType === "insert") {
const messageDetails = change.fullDocument;
pusher.trigger("messages", "inserted", {
name: messageDetails.name,
message: messageDetails.message,
timestamp: messageDetails.timestamp,
received: messageDetails.received,
});
} else {
console.log("Error triggering Pusher");
}
});
});
//api routes
app.get("/", (req, res) => {
Messages.findOne({}, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(200).send(data);
}
});
});
app.get("/messages/sync", (req, res) => {
Messages.find({}, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(200).send(data);
}
});
});
app.post("/messages/new", (req, res) => {
const dbMessage = req.body;
Messages.create(dbMessage, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
});
});
//listen
app.listen(port, () => console.log(`Listening on localhost:${port}`));