From 9d0b547e6e49a0d38dd53ff7d94943c86163b75f Mon Sep 17 00:00:00 2001 From: Gabriel Canali Date: Sat, 17 Feb 2024 21:12:38 -0300 Subject: [PATCH] feat: create display message websocket --- server/src/api/ws/display-messages.ts | 31 ++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/server/src/api/ws/display-messages.ts b/server/src/api/ws/display-messages.ts index 034cfc2..79dbc37 100644 --- a/server/src/api/ws/display-messages.ts +++ b/server/src/api/ws/display-messages.ts @@ -1,7 +1,36 @@ import { FastifyInstance } from "fastify"; +import z from "zod"; +import { getMessageHistory } from "../../utils/message-history"; +import { messageDisplay } from "../../utils/message-pub-sub"; export async function displayMessage(app: FastifyInstance) { - app.get('/api/:channel', {websocket: true}, (connection, request) => { + app.get('/api/:channel', {websocket: true}, async (connection, request) => { + const messageParam = z.object({ + channel: z.string().uuid() + }) + + type Message = { + id?: Number, + userId: Number, + channel?: string, + content: string, + created_at: Date + } + + const { channel } = messageParam.parse(request.params) + + connection.socket.send('Getting old messages, please await') + + const messageHistory = await getMessageHistory(channel) + function showMessage (message: Message) { + connection.socket.send(`${message.content} - UserID: ${message.userId}`) + } + + messageHistory.forEach(message => showMessage(message)) + + messageDisplay.subscribe(channel, (message) => { + showMessage(message) + }) }) } \ No newline at end of file