Skip to content

Expose decorated fastify server in websocket handler #66

@einnjo

Description

@einnjo

🚀 Feature Proposal

Expose decorated fastify server in websocket handler

Motivation

Currently, taking advantage of one of the use cases of decorations and the plugin system is not possible inside a websocket handler.

Decoration use case from Fastify docs:

fastify.decorate('db', new DbConnection())

fastify.get('/', async function (request, reply) {
  reply({hello: await this.db.query('world')})
})

This means that we can not take advantage of other plugins that might have been setup in our Fastify server, and must find another way to expose this functionality to the websocket handler, possibly resulting in duplicated efforts.

I looked at the source of this plugin and understand that it uses its own independent router and therefore, most of the facilities we expect inside a regular request handler are not available. I believe we can expose the Fastify server to the websocket handler with little effort to take advantage of the decorations introduced by other plugins.

Example

In Fastify handlers, this is bound to the server. I believe we can use the same strategy here, for consistency's sake, though I admit I'm not familiarized with the memory/performance implications.

fastify.get('/', { websocket: true }, function myWSHandler(connection, req) {
  // this is bound to Fastify server
  this.myPlugin.someFunc()

  connection.socket.on('message', message => {
    // message === 'hi from client'
    connection.socket.send('hi from server')
  })
})

Possible implementation?

https://github.com/fastify/fastify-websocket/blob/master/index.js#L55

      // ...
      router.on('GET', routeOptions.path, (req, _, params) => {
-      const result = wsHandler(req[kWs], req, params)
+      const result = wsHandler.call(fastify, req[kWs], req, params)

        if (result && typeof result.catch === 'function') {
          result.catch(err => req[kWs].destroy(err))
        }
      })

I'm willing to help with the implementation if you agree that this would be useful.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions