-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03-chat-api-ui.js
More file actions
42 lines (35 loc) · 1.08 KB
/
03-chat-api-ui.js
File metadata and controls
42 lines (35 loc) · 1.08 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
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
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);
app.use(express.json()); // for parsing application/json
app.get("/messages", async (req, res) => {
const collection = client.db("chat").collection("messages");
const messagesCursor = await collection.find({});
res.json(await messagesCursor.toArray());
});
app.post("/messages", async (req, res) => {
const collection = client.db("chat").collection("messages");
const newMessage = await collection.insertOne({
from: req.body.from,
text: req.body.text,
});
res.json(newMessage);
});
app.use("/", express.static("ui/dist"));
server.listen(3000, () => {
console.log("listening on *:3000");
});