-1

I have a simple websocket in fastify which calls a custom plugin i wrote:

module.exports = async function (fastify, opts) {
    fastify.register(require('@fastify/websocket'))


    fastify.register(async function (fastify) {
        fastify.get('/', { websocket: true }, (socket /* WebSocket */, req /* FastifyRequest */) => {

            socket.on('message', async (message) => {
                // read & parse raw message
                fastify.myFoo.doSomething(message, socket)
            })
        })
    })
}

Question 1:

Is there a need to pass the socket to the plugin? or since the whole websocket is being registered: fastify.register it can automatically be accessible through other plugins?

Then in myFoo plugin i want to send a message through the socket:

const fastifyPlugin = require('fastify-plugin')

async function MyFoo(fastify, options) {

    const doSomething = (rawMessage, socket) => {
        this.socket = socket
        this.rawMessage = rawMessage
    }

    const foo2 = () => {
        this.socket.send(JSON.stringify({"some message":5}))
    }

    fastify.decorate('myFoo', {
        doSomething: doSomething
    })
}

module.exports = fastifyPlugin(MyFoo)

Question 2:

If I have to pass socket as a parameter how do I make it accessible to all the other functions in the plugin? this. does not seem right here. Can I simply just declare a global variable inside MyFoo ?

Question 3:

Also I might want to call fastify.myFoo.doSomething(message, socket) multiple times. But this is not a "constructor" i.e. I will be calling the same instance of the plugin correct? (i.e. same state/context)

0