Skip to content

re-utils/ws-routers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Websocket routers

Runtime-specific websocket routers built for performance.

Bun

Example route:

import { autoRoute } from 'ws-routers/bun';

export default autoRoute<{ id: number }>({
  message: (ws, msg) => {
    ws.send(ws.data.id + ':' + msg);
  }
});

Use in a request handler:

import handleSocket from '/path/to/route';

export default (req: Request): Response => {
  // Similar to server.upgrade but run the handlers for that route only
  if (handleSocket(req, {
    id: Math.random()
  })) return;

  // Do other things...
}

And serve with autoServe instead of Bun.serve:

import { autoServe } from 'ws-routers/bun';

autoServe({
  fetch: myRequestHandler,
  port: 3000,
  // Other options...
});

Deno

Example route:

import { route } from 'ws-routers/deno';

export default route<{ id: number }>({
  message(event) {
    // Access the current socket with `this`
    // Obtain the data passed in with `this.$`
    this.send(this.$.id + ':' + event.data);
  }
});

Use in a request handler:

import handleSocket from '/path/to/route';

export default (req: Request): Response => {
  if (req.headers.get("upgrade") === "websocket") {
    // The websocket is handled by the route
    const res = handleSocket(req, {
      $: { id: Math.random() }
    });

    // Other code...

    // Then return the socket response
    return res.response;
  }

  // Do other things...
}

Cloudflare

Example route:

import { route } from 'ws-routers/cloudflare';

export default route<{ id: number }>({
  message(event) {
    // Access the current socket with `this`
    // Obtain the data passed in with `this.$`
    this.send(this.$.id + ':' + event.data);
  }
});

Use in a request handler:

import handleSocket from '/path/to/route';

export default (req: Request): Response => {
  if (req.headers.get("upgrade") === "websocket") {
    // The websocket is handled by the route
    const socketPair = handleSocket(req, { id: Math.random() });

    // Other code...

    // Then return the response with the client socket
    return new Response(null, {
      status: 101, webSocket: socketPair[0]
    });
  }

  // Do other things...
}

Events

A very simple event model.

import event from 'ws-routers/event';

// Create a topic
const [subscribers, publish] = event((subscriber, ...args) => {
  // Do something with subscriber and args...
});

// Set operations
subscribers.add(subscriber);
subscribers.remove(subscriber);

// Publish some data to all subscribers (must match callback args)
publish(...args);

About

Runtime-specific high performance WebSocket routers

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published