npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

wspromisify

v2.4.4

Published

Wraps your WebSockets into Promise-based class with full d.ts typings on client & server

Downloads

265

Readme

WebsocketPromisify

Build Status codecov bundlephobia npm Deps DevDeps

A nice-looking this readme version: https://houd1ni.github.io/WebsocketPromisify/

Makes websocket's API just like REST with Promise-like API, with native Promises. Has a lot of yummies and very lightweight (less than 3kb in gzip)!

const responseData = await ws.send({catSaid: 'Meow!'})

// If you detected some bug, want some stuff to be added, feel free to open an issue! Large data support (chunking), plugins, streams and different server-side implementations are coming. To see a Node.js server-side part example, please, take a look on test/mock in github repo.

Makes a Promise-like WebSocket connection. Features (almost all are tunable via constructor config below.)

  • Async/await ready.
  • ES-module and commonjs built-in.
  • Types (d.ts) included.
  • Automatically reconnects.
  • Supports existent native WebSocket or ws-like implementation (ws npm package) via socket property.
  • And provide your own socket instance via socket config prop.
  • Any id and data keys to negotiate with your back-end.
  • Any (serialiser)/Decoder(deserialiser).
  • Lazy connect: connects only if something sent, then send all of them!
  • Supports middleware-adapter. E.g. you can use 'ws' package in Node!
  • Custom easy .on method with or without condition: analog to .addEventListener.
  • Can log messages/frames/response time into console or wherever you want to. (Hello, firefox 57+!)
  • Any protocols field.
  • Rejects if sent into closed socket or after some timeout without response.
  • If something sent before connection is estabilished, it sends when it's ready.
  • Pings to stay connected if necessary.

How it on Server Side ?

  1. Serialized JSON is sent by this lib = {id: 'generated_id', data: your data}
     ... or some entity from your .encode function(message_id, message_data)
  2. Some Server processing...
  3. Serialized JSON is sent back by the Server = {id: 'the same generated_id', data: feedback data}
     ... or some entity that could be parsed by your .decode function(raw_data)

Default constructor config is

{
  // You can also use plain text and blobs in future.
  data_type: 'json',
  // Debug features. Not required.
    log: ((event, time, message) => null),
    // Will count milliseconds for responses and put them to log function above.
    timer: false,
  // Set up.
    // Required. URL to connect without a protocol.
    // Can start with /, then current page host and port will be used.
    url: 'localhost',
    // Timeout after sending a message before it drops with error.
    timeout: 1400,
    // Reconnect timeout in seconds or null.
    reconnect: 2,
    // Lazy connect: connects only if something sent (then sends all of them!)
    lazy: false,
    // Existing socket if you already have one to augment with this force.
    socket: null,
    // You can set your own middleware here.
    adapter: ((host, protocols) => new WebSocket(host, protocols)),
    // You can replace original serialisation to your own or even binary stuff.
    encode: (message_id, message_data, config) => data,
    // You can replace original deserialisation to your own or even
    //     making the message object from binary data.
    //     id_key and data_key could be taken from the config argument.
    decode: (raw_message) => { message_id, message_data },
    // WebSocket constructor's protocol field.
    protocols: [],
    // Unique id's and data keys to negotiate with back-end.
    server: {
      id_key: 'id',
      data_key: 'data'
    },
    // Pings to avoid interruptions. null to disable.
    ping: {
      interval: 55, // seconds.
      content: {} // goes to `data` => { id, data: {} } by default.
    }
}

Fields/Props:


  // read-only, returns WebSocket (or so) instance to use with other stuff.
  socket

Methods:


  // Returns Promise that connection is open. Works even if it already opened.
  ready()
  // sends any type of message and returns a Promise.
  send(message),
  // .addEventListener with optional predicate that works after reconnections.
  on(event_name, handler, predicate = (WebSocketEvent) => true),
  // Closes the connection and free up memory. Returns Promise that it has been done.
  close()

Example:


  import WSP from 'wspromisify' // or const WSP = require('wspromisify') in Node.

  const somehost = 'example.com:8080'

  const someFunction = async () => {
    const ws = new WSP({
      // If url starts with /,
      // it results in ws(s if in https)://currentHost:currentPort/thisUrl
      url: 'ws://example.com/ws',
      timeout: 2e3, // 1400ms by default.
      timer: true, // false by default.
      // To log data trips. Events: open, close, send, reconnect, error.
      // If timer isn't enabled, the signature is log(event, message)
      log(event, time, message = '') {
        if(time !== null) {
          console.log(event, `in ${time}ms`, message)
        } else {
          console.log(event, message)
        }
      }
    })

    try {
      // You can wait for ready by calling await ws.ready() or send it right now:
      // the messages will be sent as soon as the connection is opened.
      const data = await ws.send({catSaid: 'Meow!'})
      console.log({data})
    } catch(error) {
      console.error('Cannot send a message due to ', error)
    }
  }

  someFunction()