fastify / fastify/fastify-websocket

Message Validations

Open
#190 7 comments 1 reaction 0 assignees View on GitHub
Dominant language
JavaScript
Stars
468
Forks
84
PR merge metrics
No merged PRs in 30d

Description

### Prerequisites

- [X] I have written a descriptive issue title
- [X] 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.

```js
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
```js
if (routeOptions.websocket || routeOptions.wsHandler) {
let wsSchema = routeOptions.schema // otherwise the onUpgrade fails with invalid body
delete routeOptions.schema
```

### Motivation

Reviving https://github.com/fastify/help/issues/102
It would be great to have message validations based on the route schemas

### Example

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.