-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
84 lines (70 loc) · 2.05 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
import express from "express"
import mongoose from "mongoose"
import Messages from "./dbMessages.js"
import Pusher from "pusher"
import cors from "cors"
import 'dotenv/config'
const app = express()
const port = process.env.PORT
const pusher = new Pusher({
appId: "1609032",
key: "b8255243c6e1dc4858f6",
secret: "e7a003ab7d33f44e4809",
cluster: "ap2",
useTLS: true
});
app.use(express.json())
app.use(cors())
const connection_url = process.env.MONGO_URL
mongoose.connect(connection_url, {})
app.get("/", (req, res) => {
res.status(200).send("hello world, how you doing?" )
})
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")
}
})
})
app.get("/messages/sync", async (req, res) => {
try {
const mData = await Messages.find({});
res.status(200).send(mData);
} catch (err) {
res.status(500).json({ success: false, message: 'Fetching posts failed, please try again' });
}
// Messages.find({})
// .then((data) => {
// res.status(200).send(data)
// })
// .catch((err) => {
// res.status(500).send(err)
// })
})
app.post("/messages/new", (req, res) => {
const dbMessage = req.body
Messages.create(dbMessage)
.then((data) => {
res.status(201).send(data)
})
.catch((err) => {
res.status(500).send(err)
})
})
app.listen(port,() => {
console.log(`Listening on localhost:${port}`);
})