-
-
Notifications
You must be signed in to change notification settings - Fork 83
Description
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.schemaMotivation
Reviving fastify/help#102
It would be great to have message validations based on the route schemas
Example
No response