34
loading...
This website collects cookies to deliver better user experience
const { WebPubSubServiceClient } = require('@azure/web-pubsub')
const CONN_STR = process.env.PUBSUB_CONNECTION_STRING
const HUB = process.env.PUBSUB_HUB
const serviceClient = new WebPubSubServiceClient(CONN_STR, HUB)
const eventName = req.headers['ce-eventname']
const userId = req.headers['ce-userid']
if (eventName === 'createChat') {
// Build custom event payload
const chatPayload = {
id: req.body.id,
name: req.body.name,
owner: userId
}
// ... Update state, removed for brevity ...
// Send message to all clients with custom JSON payload
// Will be routed via Azure Web PubSub with WebSocket protocol
serviceClient.sendToAll({
chatEvent: 'chatCreated',
data: JSON.stringify(chatPayload),
})
}
// Get URL & token to connect to Azure Web Pubsub
res = await fetch(`/api/getToken?userId=${userId}`)
let token = await res.json()
// Now connect to Azure Web PubSub using the URL we obtained
let ws = new WebSocket(token.url, 'json.webpubsub.azure.v1')
ws.send(
JSON.stringify({
type: "event",
event: "createChat",
dataType: "json",
data: { name: chatName, id: chatId },
})
);
ws.send(
JSON.stringify({
type: "sendToGroup",
group: chatId,
dataType: "json",
data: {
message: message,
fromUserId: userId,
},
})
);