Code Monkey home page Code Monkey logo

websocketpromisify's Introduction

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()

websocketpromisify's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

websocketpromisify's Issues

close event not called

on('close', () => {}) not called,messages not clean when ws closed. it will send message multiply.

Wrong entry point in package.json

Hi,

I start using wspromisify in my Quasar project, based on VIte, and get the following error on build:

[vite] Internal server error: Failed to resolve entry for package "wspromisify". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "wspromisify". The package may have incorrect main/module/exports specified in its package.json.
Plugin: vite:import-analysis
File: ui/src/api/wsp.ts
at packageEntryFailure (ui/node_modules/vite/dist/node/chunks/dep-689425f3.js:40970:11)
at resolvePackageEntry (ui/node_modules/vite/dist/node/chunks/dep-689425f3.js:40966:9)
at tryNodeResolve (ui/node_modules/vite/dist/node/chunks/dep-689425f3.js:40773:20)
at Context.resolveId (ui/node_modules/vite/dist/node/chunks/dep-689425f3.js:40581:28)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.resolveId (ui/node_modules/vite/dist/node/chunks/dep-689425f3.js:39254:32)
at async TransformContext.resolve (ui/node_modules/vite/dist/node/chunks/dep-689425f3.js:39028:23)
at async normalizeUrl (ui/node_modules/vite/dist/node/chunks/dep-689425f3.js:58354:34)
at async TransformContext.transform (ui/node_modules/vite/dist/node/chunks/dep-689425f3.js:58509:57)
at async Object.transform (ui/node_modules/vite/dist/node/chunks/dep-689425f3.js:39317:30)

And actually it is not correct:
Screenshot 2023-02-25 at 11 27 34

Custom id_key function

Hey!

I am trying to use your framework but I already have my own custom id_key function which I NEED to use.

I basically use a spellchecker!

Imagine this flow:

text change #1 => websocket id_key 1
text change #2 => websocket id_key 2

websocket id_key 2 response
websocket id_key 1 response

Without any ability to manage my id_key the id_key 1 response is what is going to be saved on the interface. Which is wrong because it is outdated. It happens a lot of times that the server is slow and unpredictable to respond.

Therefore I need a way to discard "old" responses that I dont want.

I did this before by creating my own id_key with a simple JS date.toString().

But it can get even more wacky and crazy because I have several independent sentences that have different errors like so:

text change #1 on sentence #1 => websocket id_key 11
text change #2 on sentence #1 => websocket id_key 21

text change #1 on sentence #2 => websocket id_key 12

websocket id_key 21 response => i want this response
websocket id_key 12 response => i also want this one because it is from a different sentence

So I need a way to manage this complexity, and the way I do this is to have my very own custom identifier that i send to the server so that I can compare.

With your framework I need to use your message_id value that comes from the encode function and I have no way of managing this.

Can you help me out here?
Do you have any suggestions or alternatives that could help me with my use case?

TLDR: How can I ignore specific request responses based that are "older" that I no longer want to act on their response.

Im willing to talk a bit more if you think this kind of problem is interesting to you or If I am completely misunderstanding your framework.

Implement .prepare() or smth like that.

Sometimes it's useful to make parallel computations while having custom .encode and .decode adapters.
I.e. if these are compressors that require heavy load, it could be handy to prepare some messages, while others are being sent.
It should avoid code duplication and dirty tricks like flag injections.

Make wiki with common receipts.

Sometimes it's a bit hard to find solution in ways that are very common like this #23

It would be cool to make a receipt book in the Wiki here.

WebSocket is not defined

Hello, I am really interested in using this dependency, but sadly can't get it to work in my node.js project with the adjusted sample code.
If I try to run it, I receive this error, even tho I have WS installed as well. Can you help me out with this?
(node:18596) UnhandledPromiseRejectionWarning: ReferenceError: WebSocket is not defined

Add wiki.

  • client examples.
  • server examples.

Rebuild test suite.

It should be rebuilt, because the old one is too broken. After this, a lot of other issues can be done.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.