This package is a fork of fastify-websocket
and rewritten as Typescript. It provides more utility for using the websocket, e.g. boardcast
.
npm install @kakang/fastify-ws --save
yarn add @kakang/fastify-ws
After regitered the plugin, you can pass { ws: true }
to the route option. By default, it accepts the websocket handler when using the shorten method.
import Fastify from 'fastify'
import { fastifyWS } from '@kakang/fastify-ws'
fastify.register(fastifyWS)
fastify.get('/', { ws: true }, (request /* WebsocketFastifyRequest */) => {
const { socket } = request.ws
socket.on('message', message => {
// message.toString() === 'hi from client'
socket.send('hi from server')
})
})
WebsocketFastifyRequest is extended from FastifyRequest and provide some utility for websocket usage.
Subscribe to a topic.
import Fastify from 'fastify'
import { fastifyWS } from '@kakang/fastify-ws'
fastify.register(fastifyWS)
fastify.get('/', { ws: true }, (request /* WebsocketFastifyRequest */) => {
const { subscribe } = request.ws
subscribe('foo')
})
Unsubscribe from a topic.
import Fastify from 'fastify'
import { fastifyWS } from '@kakang/fastify-ws'
fastify.register(fastifyWS)
fastify.get('/', { ws: true }, (request /* WebsocketFastifyRequest */) => {
const { unsubscribe } = request.ws
unsubscribe('foo')
})
Boardcast to all websocket except itself.
import Fastify from 'fastify'
import { fastifyWS } from '@kakang/fastify-ws'
fastify.register(fastifyWS)
fastify.get('/', { ws: true }, (request /* WebsocketFastifyRequest */) => {
const { boardcast } = request.ws
boardcast('hello all.')
})
This plugin also decorate the fastify instance to provide more ability for normal route communicate to the websocket.
ws
Server instance.
import Fastify from 'fastify'
import { fastifyWS } from '@kakang/fastify-ws'
fastify.register(fastifyWS)
fastify.ws.server // ws instance
All avaiable websocket clients. It is a shortcut of fastify.ws.server.clients
import Fastify from 'fastify'
import { fastifyWS } from '@kakang/fastify-ws'
fastify.register(fastifyWS)
fastify.ws.clients // websocket clients
fastify.ws.server.clients = fastify.ws.clients // true
All topics that have registered before.
import Fastify from 'fastify'
import { fastifyWS } from '@kakang/fastify-ws'
fastify.register(fastifyWS)
for(const topic of fastify.ws.topics) {
console.log(topic)
}
All topic with WebsocketFastifyRequest.
import Fastify from 'fastify'
import { fastifyWS } from '@kakang/fastify-ws'
fastify.register(fastifyWS)
for(const [topic, requests] of fastify.ws.topicMap.entries()) {
for(const request of requests) {
console.log(topic, request)
}
}
Boardcast to all websocket.
import Fastify from 'fastify'
import { fastifyWS } from '@kakang/fastify-ws'
fastify.register(fastifyWS)
fastify.ws.boardcast('hello all.')
Boardcast to all websocket in specified topic.
import Fastify from 'fastify'
import { fastifyWS } from '@kakang/fastify-ws'
fastify.register(fastifyWS)
fastify.ws.boardcastToTopic('foo', 'hello foo.')