Skip to content

Message Validations #190

Open
Open
@zekth

Description

@zekth

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

What i'm suggesting is using the route schema available already in fastify route definition and use it to validate messages payload.

  const handleUpgrade = (rawRequest, validate, callback) => {
    wss.handleUpgrade(rawRequest, rawRequest[kWs], rawRequest[kWsHead], (socket) => {
      wss.emit('connection', socket, rawRequest)
      
      const connection = WebSocket.createWebSocketStream(socket, opts.connectionOptions)
      connection.socket = socket
      connection.socket.on('message',(message)=>{
        // we would need something like so
        if(!validate(message)) {
          connection.socket.send('RIP')
        } else {
          connection.socket.emit('parsedMessage', {foo:'bar'}) // we emit a parsed message event
        }
      })
      connection.socket.on('newListener', event => {
        if (event === 'message') {
          connection.resume()
        }
      })

      callback(connection)
    })
  }

Constraint here is we cannot unemit an event on the socket, i propose the parsedMessage event which is used for the validation. message event handler will still listen to all the events.

Problem currently is we cannot have access to the ajv-compiler from the fastify instance. If we can have access to it on within the instance or the onRoute hook we can compile the schema from the route option and create the validation function for the websocket connection.

What do you think?

note: also slight change needed in the onRoute hook

    if (routeOptions.websocket || routeOptions.wsHandler) {
      let wsSchema = routeOptions.schema // otherwise the onUpgrade fails with invalid body
      delete routeOptions.schema

Motivation

Reviving fastify/help#102
It would be great to have message validations based on the route schemas

Example

No response

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