-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04-chat-socket-ui.js
More file actions
58 lines (50 loc) · 1.38 KB
/
04-chat-socket-ui.js
File metadata and controls
58 lines (50 loc) · 1.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
/*
* HTTP SERVER - UI ONLY
*/
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
app.use("/", express.static("ui/dist"));
server.listen(3000, () => {
console.log("listening on *:3000");
});
/*
* MONGO
*/
const { MongoClient } = require("mongodb");
const CONNECTION_STRING = "mongodb://localhost:27017"; // TODO move to env
const client = new MongoClient(CONNECTION_STRING);
async function connect() {
try {
await client.connect();
} catch (e) {
console.error(e);
await client.close();
process.exit(0);
}
}
connect().catch(console.dir);
async function getMessages() {
const collection = client.db("chat").collection("messages");
const messagesCursor = await collection.find({});
return await messagesCursor.toArray();
}
async function addMessage(msg) {
const collection = client.db("chat").collection("messages");
const insRes = await collection.insertOne(msg);
return { ...msg, _id: insRes.insertedId };
}
/*
*SOCKET.IO
*/
const { Server } = require("socket.io");
const io = new Server(server);
io.on("connection", async (socket) => {
io.emit("chat history", await getMessages());
socket.on("chat message", async (msg) => {
console.log("chat message: saving, " + JSON.stringify(msg));
const newMsg = await addMessage(msg);
io.emit("chat message", newMsg);
});
});