-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
220 lines (190 loc) · 5.3 KB
/
index.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
const express = require("express")
const cors = require("cors")
const { v4: uuidv4 } = require("uuid")
const WebSocket = require("ws")
const mongodb = require("mongodb")
const { object, string, number } = require("yup")
const MongoClient = mongodb.MongoClient
const app = express()
app.use(cors())
const port = process.env.PORT || 3000
const wss = new WebSocket.Server({ noServer: true })
const mongoUrl = process.env.DB_URL
const dbName = "chatdb"
let db
const postSchema = object({
id: string()
.required()
.matches(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
author: string().required().default("Anonymous"),
content: string().required(),
createdAt: number().required(),
})
MongoClient.connect(
mongoUrl,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
if (err) {
return console.log(err)
}
db = client.db(dbName)
db.createCollection("channels", (err, res) => {
if (err) {
console.log(err)
} else {
console.log("Created channels collection")
}
})
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`)
})
}
)
app.get("/", (req, res) => {
res.send("Welcome to the iOstagram API!")
})
app.get("/channels", async (req, res) => {
try {
const channels = await db.collection("channels").find().toArray()
const channelsWithPosts = await Promise.all(
channels.map(async (channel) => ({
...channel,
posts: await db.collection(`${channel.name}_posts`).find().toArray(),
}))
)
return res.json(channelsWithPosts)
} catch (error) {
return res.status(500).send(error.message)
}
})
app.post("/channels", async (req, res) => {
try {
const channelName = req.query.channel
if (!channelName || typeof channelName !== "string") {
return res.status(400).send("Channel name is required")
}
const existingChannel = await db
.collection("channels")
.findOne({ name: channelName })
if (existingChannel) {
return res.status(400).send("Channel already exists")
}
const newChannel = { id: uuidv4(), name: channelName, posts: [] }
db.createCollection(`${channelName}_posts`, (err, res) => {
if (err) {
console.log(err)
return res.status(500).send(err)
} else {
console.log(`Created ${channelName}_posts collection`)
}
})
await db.collection("channels").insertOne(newChannel)
return res.json(newChannel)
} catch (error) {
return res.status(500).send(error.message)
}
})
app.delete("/channels", async (req, res) => {
try {
const channelName = req.query.channel
if (!channelName || typeof channelName !== "string") {
return res.status(400).send("Channel name is required")
}
const channel = await db
.collection("channels")
.findOne({ name: channelName })
if (!channel) {
return res.status(404).send("Channel not found")
}
await db.collection("channels").deleteOne({ name: channelName })
await db.collection(`${channelName}_posts`).drop()
return res.status(204).send("Channel deleted")
} catch (error) {
return res.status(500).send(error.message)
}
})
app.get("/posts", async (req, res) => {
try {
const channelName = req.query.channel
if (!channelName || typeof channelName !== "string") {
return res.status(400).send("Channel name is required")
}
const channel = await db
.collection("channels")
.findOne({ name: channelName })
if (!channel) {
return res.status(404).send("Channel not found")
}
const limit = parseInt(req.query.limit, 10) || 10000
const posts = await db
.collection(`${channelName}_posts`)
.find()
.sort({ createdAt: 1 })
.limit(limit)
.toArray()
return res.json(posts)
} catch (error) {
return res.status(500).send(error.message)
}
})
app.post("/posts", express.json(), async (req, res) => {
try {
const channelName = req.query.channel
if (!channelName || typeof channelName !== "string") {
return res.status(400).send("Channel name is required")
}
const channel = await db
.collection("channels")
.findOne({ name: channelName })
if (!channel) {
return res.status(404).send("Channel not found")
}
const rawPost = req.body
if (!rawPost) {
return res.status(400).send("Post is required")
}
let post
try {
post = await postSchema.cast(rawPost)
} catch (e) {
console.error(e)
return res.status(400).send("Invalid post")
}
await db.collection(`${channelName}_posts`).insertOne(post)
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(post))
}
})
return res.status(201).send("Post made")
} catch (error) {
return res.status(500).send(error.message)
}
})
wss.on("connection", (ws) => {
ws.on("post", async (content) => {
try {
const body = JSON.parse(content)
let newPost = body.post
const channel = await db
.collection("channels")
.findOne({ name: body.channel })
if (!channel) {
throw new Error("Channel does not exist")
}
await db.collection(`${body.channel}_posts`).insertOne(newPost)
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(content)
}
})
} catch (error) {
console.error("Error processing post:", error)
}
})
})
app.on("upgrade", (request, socket, head) => {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit("connection", ws, request)
})
})