Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
188 lines (160 loc) · 4.34 KB
/
Copy pathapp.js
File metadata and controls
188 lines (160 loc) · 4.34 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
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
'use strict'
const { join } = require('node:path')
const fastify = require('fastify')({
logger: {
transport: {
target: 'pino-pretty',
options: {
colorize: true
}
}
}
})
const { randomSuperhero } = require('superheroes')
const shortid = require('shortid')
// you can use any queue system for delivering a message
// across multiple server instances, see https://www.npmjs.com/package/mqemitter.
const mq = require('mqemitter')
const emitter = mq({ concurrency: 5 })
// our database
const db = new Map()
fastify
// remember to configure the content security policy as well!
.decorateRequest('user', null)
.register(require('@fastify/cookie'), { secret: 'supersecret' })
.register(require('@fastify/formbody'))
.register(require('@fastify/websocket'), { clientTracking: true })
.register(require('..'), {
templates: join(__dirname, 'views'),
filename: join(__dirname, 'worker.js')
})
// every time we have a new message, let's broadcast it
emitter.on('new-message', (message, _cb) => {
for (const socket of fastify.websocketServer.clients.values()) {
socket.send(message.payload)
}
})
emitter.on('delete-message', (message, _cb) => {
for (const socket of fastify.websocketServer.clients.values()) {
socket.send(message.payload)
}
})
// render the initial page and populate it
// with the current content
fastify.get('/', async (req, reply) => {
const messages = []
for (const [id, message] of db.entries()) {
messages.push({ id, text: message.text, user: message.user })
}
const existing = req.cookies.user && req.unsignCookie(req.cookies.user)
const username =
existing && existing.valid
? existing.value
: `${randomSuperhero()}-${shortid.generate()}`
if (!existing || !existing.valid) {
reply.setCookie('user', username, {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
sameSite: true,
path: '/',
signed: true
})
}
return reply.render('index.svelte', { messages, username })
})
// post a new message!
fastify.route({
method: 'POST',
path: '/message',
onRequest: authorize,
handler: onCreateMessage
})
async function onCreateMessage (req, reply) {
const id = shortid.generate()
req.log.info(`creating new message with id ${id} from user ${req.user}`)
db.set(id, {
text: req.body.content,
user: req.user
})
const payload = await reply.turboGenerate.append(
'message.svelte',
'messages',
{
message: {
id,
text: req.body.content,
user: req.user
}
}
)
emitter.emit({
topic: 'new-message',
payload
})
return reply.redirect('/')
}
// delete a message, users can only delete
// their own messages
fastify.route({
method: 'POST',
path: '/message/:id/delete',
onRequest: authorize,
handler: onDeleteMessage
})
async function onDeleteMessage (req, reply) {
// in production ensure to validate or sanitize the user provided id
const { id } = req.params
req.log.info(`deleting message ${id}`)
if (!db.has(id)) {
return reply.turboStream.replace('toast.svelte', 'toast', {
text: `The message with id ${id} does not exists`
})
}
const message = db.get(id)
if (message.user !== req.user) {
return reply.turboStream.replace('toast.svelte', 'toast', {
text: "You can't delete a message from another user"
})
}
db.delete(id)
const payload = await reply.turboGenerate.remove(
'message.svelte',
`message_frame_${id}`,
{ message: { id } }
)
emitter.emit({
topic: 'delete-message',
payload
})
return { acknowledged: true }
}
// remove a toast
fastify.route({
method: 'POST',
path: '/toast/ack',
onRequest: authorize,
handler: onAckToast
})
async function onAckToast (_req, reply) {
return reply.turboStream.remove('toast.svelte', 'toast')
}
fastify.register(async function (fastify) {
fastify.get('/ws', { websocket: true }, (_socket, req) => {
req.log.info('new websocket connection')
})
})
// authenticate client requests
async function authorize (req, reply) {
const { user } = req.cookies
if (!user) {
reply.code(401)
throw new Error('Missing session cookie')
}
const cookie = req.unsignCookie(user)
if (!cookie.valid) {
reply.code(401)
throw new Error('Invalid cookie signature')
}
req.user = cookie.value
}
fastify.listen({ port: 3000 })