Skip to content

Commit

Permalink
Simplify the API from wsServer and opts.wsLibrary to ws and opts.library
Browse files Browse the repository at this point in the history
  • Loading branch information
gj committed Oct 28, 2017
1 parent f881a37 commit 43a95af
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 14 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ In `server.js`:
const fastify = require('fastify')()

fastify.register(require('fastify-ws'), {
wsLibrary: 'uws' // Use the uws library instead of the default ws library
library: 'uws' // Use the uws library instead of the default ws library
})

fastify.ready(err => {
if (err) throw err

fastify.wsServer
.on('connection', ws => {
ws.on('message', msg => ws.send(msg)) // Creates an echo server
fastify.ws
.on('connection', socket => {
socket.on('message', msg => socket.send(msg)) // Creates an echo server
})
})

Expand Down
8 changes: 4 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
const fp = require('fastify-plugin')

module.exports = fp((fastify, opts, next) => {
const wsLib = opts.wsLibrary || 'ws'
const lib = opts.library || 'ws'

if (wsLib !== 'ws' && wsLib !== 'uws') return next(new Error('Invalid "wsLibrary" option'))
if (lib !== 'ws' && lib !== 'uws') return next(new Error('Invalid "library" option'))

const WebSocketServer = require(wsLib).Server
const WebSocketServer = require(lib).Server
const wss = new WebSocketServer({
server: fastify.server
})

fastify.decorate('wsServer', wss)
fastify.decorate('ws', wss)

next()
})
12 changes: 6 additions & 6 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ test('expose a WebSocket', t => {
fastify.ready(err => {
t.error(err)

fastify.wsServer
.on('connection', ws => {
ws.send('hello client')
fastify.ws
.on('connection', socket => {
socket.send('hello client')

ws.on('message', msg => {
socket.on('message', msg => {
t.equal(msg, 'hello server')

ws.terminate()
fastify.wsServer.close(() => fastify.close())
socket.terminate()
fastify.ws.close(() => fastify.close())

process.exit()
})
Expand Down

0 comments on commit 43a95af

Please sign in to comment.