1.0.1 • Published 5 years ago

simple-ws-wrapper v1.0.1

Weekly downloads
4
License
MIT
Repository
github
Last release
5 years ago

Build Status version downloads MIT License

PRs Welcome Code of Conduct

Watch on GitHub Star on GitHub Tweet

This lib is isomorphic, so it works on both node (using ws) and on browsers (using the native WebSocket class).

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install --save simple-ws-wrapper

The problem

There are a lot of libraries that provide a great API for interacting via WebSockets, but most of them require a custom client to use it. Because of this, it becomes harder to use them on a cross-platform environment (e.g. the server made using node and the client being a native mobile app). Because they do not work with native WebSocket clients, if the library does not provide the client for accessing it on the environment you are using, you just cannot use it.

As an alternative we could use libraries like ws, which does not require any client package to interact with the server, but unfortunately it does not provide the best of the API's for that, so you end up with a lot of weird boilerplate just to manage the messages.

This solution

When using on a node environment, this is just a simple wrapper around ws, and when on browsers, it is a wrapper around the native WebSocket class. In both cases, we provide the same socket.io inspired API for exchanging messages between server and client.

Because ws works natively with native websocket clients, if you create a server using this package, you can use it in whatever enviromnent which supports websockets without any additional package.

Under the hood, we work with objects with the shape below, so if you don't plan to use our wrapper on the client as well, you can just send an object with that shape and everything will work the same.

{
  type: string;
  data?: any;
}

Usage

Server

const ws = require('ws')
const SocketWrapper = require('simple-ws-wrapper')

const socket = new SocketWrapper(new ws.Server({ port: 3000 }))

const messages = []

socket.on('connection', () => {
  socket.emit(
    'welcome',
    'Welcome! You have successfully connected to the server',
  )
})

socket.on('request-initial-data', () => {
  socket.emit('initial-data', { name: 'James', surename: 'Bond' })
})

socket.on('add-message', (message) => {
  messages.push(message)
  console.log(messages) // [{ date: "2019-02-09T13:53:52.058Z", message: "hey there!" }]
})

Client

const WebSocket = require('ws')
const SocketWrapper = require('simple-ws-wrapper')

const socket = new SocketWrapper(new WebSocket('ws://localhost:3000'))

socket.on('welcome', (data) => {
  console.log(data) // "Welcome! You have successfully connected to the server"
})

socket.on('initial-data', (data) => {
  console.log(data) // { name: "James", surename: "Bond" }
})

const onConnect = async () => {
  await socket.waitConnection()
  socket.emit('request-initial-data')
  socket.emit('add-message', {
    date: '2019-02-09T13:53:52.058Z',
    message: 'hey there!',
  })
}

onConnect()

Browser

Browser usage is essentially the same as described in Client above, the only difference is that you use the native WebSocket class, instead of the ws package.

API

.emit(type: string, data?: any): void

Emits a message of given type to all listeners.

type: Type of the message which will be sent.

data: Optional. Data of the message.

socket.emit('request-initial-data')
socket.emit('add-message', {
  date: '2019-02-09T13:53:52.058Z',
  message: 'hey there!',
})

.on(type: string, handler: (data: any) => void): void

Adds a listener on given type message.

type: Which message will be listened.

handler: Function to be executed when given type is called. The first argument of the function is the data of the message.

socket.on('add-message', (data) => {
  console.log(data) // { date: "2019-02-09T13:53:52.058Z", message: "hey there!" }
})

.waitConnection(): Promise<void>

On a server, will resolve when a client has connected.

On a client, will resolve when it connects to the server.

Inspiration

The API is heavily inspired by the awesome socket.io.

Other Solutions

  • ws: The library which we use internally to provide the wrapper.

I'm not aware of any others, if you are please make a pull request and add it here!

LICENSE

MIT