Skip to content

Commit

Permalink
feat: create display message websocket
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielcanali committed Feb 18, 2024
1 parent 92a9978 commit 9d0b547
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion server/src/api/ws/display-messages.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
}

0 comments on commit 9d0b547

Please sign in to comment.