Skip to content

Instantly share code, notes, and snippets.

@prav-raghu
Created August 31, 2021 19:08
Show Gist options
  • Save prav-raghu/56fa42f47339c362dab93793bae32bf4 to your computer and use it in GitHub Desktop.
Save prav-raghu/56fa42f47339c362dab93793bae32bf4 to your computer and use it in GitHub Desktop.
Fastify ws socket
// [the entire purpose of this exercise is to make a post request that will emit an event that takes in an id that should match up with one of the connected socket clients
// if we get this process right it will not only help with our payment work thats being worked on but any future dashboard realtime updates for stats]
// step processes work as follows with no auth considered in this code
// 1) make a post request with a unique identifier attached to it
// 2) if there exists a client with said matching unique identifier thats currently open accept that message from the server
// 3) we can choose in this case to then close the connection for that client
// ** lets assume this is what would done for the payment
// [feed back will be much appreciated]
'use strict';
import { v4 as uuidv4 } from "uuid";
const events = require('events');
const eventEmitter = new events.EventEmitter();
const ws = require('fastify-websocket');
const fastify = require('fastify')({
http2: false,
logger: true,
});
// [register web socket]
fastify.register(ws, { options: { maxPayload: 1048576 } });
// [socket connection with will also be appended with an id thats made by the client]
// [can be client id]
// [unique identifier]
// [example : to make a connect will be ws://localhost:3000/001671CE-2F21-4C42-A4A7-ADD94A98EE92]
fastify.route({
method: 'GET',
url: '/:id',
handler: (req: any, reply: any) => {
reply.send({ hello: 'world' })
},
wsHandler: (conn: any, req: any) => {
let id = req.url.substring(req.url.lastIndexOf("/") + 1);
conn.socket.id = id;
conn.socket.on('message', (message: any) => {
conn.socket.id = uuidv4();
conn.socket.send('hi from server')
})
}
});
// [post request that consists of a body with the following payload]
// [id will be used to match up with requested client socket]
// {
// "id": "001671CE-2F21-4C42-A4A7-ADD94A98EE92",
// "greeting":"Hello"
// }
fastify.route({
method: "POST",
url: '/notify',
handler: (req: any, reply: any) => {
eventEmitter.emit('connection', req.body);
reply.send({ status: 'ok' });
},
});
// [emit to broadcast data]
eventEmitter.on('connection', (data: any) => {
let isSuccessfulBroadCast = broadcast(data);
return isSuccessfulBroadCast;
});
const broadcast = function (value: any) {
// [broadcast to specific socket clients]
let messageSentToClient = false;
fastify.websocketServer.clients.forEach(function each(client: any) {
// [values from the post request need to match up with the request to the socket end point that has a parameter]
if (client.id === value.id) {
// [check client status]
if (client.readyState === 1) {
client.send(value.greeting);
messageSentToClient = true;
client.close();
}
}
});
return messageSentToClient;
}
// [listen on port]
fastify.listen(3000, (err: any) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
});
// [ass]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment