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

state-scoket.io

v0.0.1

Published

A simple state syncing middleware for Socket.io.

Downloads

7

Readme

state-socket.io

A simple state syncing middleware for Socket.io.

The problem it solves

In most cases you don't need a complex server side logic, just a simple service that syncronize the app's states between the clients. This middleware does exactly the same. It is great for client heavy applications, where the client handles the business logic.

  • The clients can update the state, by emitting an update event.
  • Any client can get the current state, by emitting a get event.
  • Any client can subscribe to the notify event, where the updates from the other clients are sent.
  • The middleware handle the out of date sync, when the client not updating the latest state.

Status of the package

Package is under development, it hasn't been ready for public usage yet. It is open for development, but some tests, guidelines and automated piplines are missing.

Getting started

Peer Dependencies

  • socket-io: 4.x

Install package

npm i state-socket.io socket-io

Creating a server

Simply use the createStateMiddleware() function as a socket.io middleware.

// server.js

const { createServer } = require('http')
const { Server } = require('socket.io')
const { createStateMiddleware } = require('state-scoket.io')

const httpServer = createServer()
const io = new Server(httpServer, { path: '/socket.io/' })
io.use(createStateMiddleware())

io.on("connection", (socket) => {
  console.log("[socket.io] Connected.")
});

SERVER_PORT=3000
httpServer.listen(SERVER_PORT, () => {
  console.log(`[http server] started on http://localhost:${SERVER_PORT}`)
});

Using in a client

The following events can be emitted:

  • scoket.emit('get', callback):
    • Get the current state.
    • The callback is called, with error first syntax: (error, data) => {}
    • Response data in the callback {updateId: '<some random id>', state: {}}
    • The initial state is null.
  • socket.emit('update', params, callback)
    • Updates the current state with a new one. It is not trigger a notify event for the current client just for the others.
    • params:
      • updateId: The server needs the latest update ID, to avoid state overrides from other clients.
        • If the client do not send the latest update id, it will result an error.
        • The latest update ID can be consumed from the notify event or from the get and update callbacks.
      • newState: The new state. It van be any data, typically an object. You need the previous state, if you want to change that.
    • callback: (error, data) => {}
      • Error first syntax.
      • Response data in the callback {updateId: '<some random id>', state: {}}
const socket = io({ transports: ['websocket'] })
socket.on('connect', () => {
  // the client needs the latest update ID to update the current state.
  let = updateId

  // getting the current state
  socket.emit('get', (error, data) => {
    console.log(`updateId`: data.updateId, `current state`: data.state)
    updateId = data.updateId
  }

  // updating the state
  socket.emit(
    'update', 
    { updateId, newState: {someKey: 'value'} }, 
    (error, data) => {
      console.log(`updateId`: data.updateId, `current state`: data.state)
      updateId = data.updateId
    }
  )

  // get notification of the updates done by other clients
  socket.on('notify', (data) => {
    console.log(data)
    updateId = data.updateId
  })
}

Error handling

The error variable in the callback is a string with a following values:

  • outdated_update: not the latest udpateId is used. Get the new udpateId or retry the udpate event.
  • internal_server_error: some unexpected error is happened in the middleware, check the server logs.

Examples

Check the example subdir for a basic working example A basic example

If you check out the repo, you can run the example with:

npm i && npm run example

Then naviagte to the URL provided by the console.

Roadmap

v1.0.0 - 1st public release

  • [x] Basic functionality (update, get, notify)
  • [ ] Integration tests through socket.io
  • [x] Working unit tests
  • [x] working examples
  • [ ] check compatbility w namespaces, add an example too
  • [ ] nicer examples
  • [x] documentation (usage)
  • [ ] create test pipeline
  • [ ] contribution / development docs

next

  • [ ] Typescript
  • [ ] more sophisitcated update handling
  • [ ] Abstract the store adapter
  • [ ] room support
  • [ ] remove data if nobody in the room
  • [ ] Update history, rollback
  • [ ] Inroduce Typescript
  • [ ] Remove data based on timestamp
  • [ ] support custom event names
  • [ ] Add a working server out of the box
    • [ ] with configurable namespaces