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 🙏

© 2025 – Pkg Stats / Ryan Hefner

gin-websocket-client

v1.2.0

Published

TypeScript/JavaScript client for gin-websocket with fetch interface and event subscriptions

Readme

gin-websocket-client

TypeScript/JavaScript client for gin-websocket with a fetch-compatible API and elegant event subscriptions using pica-route.

Features

  • fetch-compatible API - Drop-in replacement for window.fetch() over WebSocket
  • Event subscriptions - Subscribe to server push events with pica-route patterns
  • Pattern matching - Use :params and * wildcards in subscription patterns
  • Auto-reconnect - Configurable automatic reconnection
  • TypeScript - Full TypeScript support with type definitions

Installation

npm install gin-websocket-client

Quick Start

import { WsClient } from 'gin-websocket-client';

// Create client
const client = new WsClient('ws://localhost:8080/ws');

// Make requests using fetch API
const response = await client.fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Alice' })
});
const data = await response.json();

// Subscribe to server push events
client.subscribe('/events/user/created', (event) => {
  console.log('New user:', new TextDecoder().decode(event.data));
});

// Pattern matching with params
client.subscribe('/notifications/:type', (event, params) => {
  console.log(`Notification type: ${params.type}`);
});

// Wildcard subscriptions
client.subscribe('/events/*', (event) => {
  console.log('Event:', event.route);
});

API

WsClient

Constructor

const client = new WsClient(url: string, options?: WsClientOptions)

Options:

interface WsClientOptions {
  reconnect?: boolean;              // Enable auto-reconnect (default: true)
  reconnectInterval?: number;       // Reconnect delay in ms (default: 1000)
  maxReconnectAttempts?: number;    // Max reconnect attempts (default: 5)
}

Example:

const client = new WsClient('ws://localhost:8080/ws', {
  reconnect: true,
  reconnectInterval: 2000,
  maxReconnectAttempts: 10
});

Methods

fetch

client.fetch(url: string, init?: RequestInit): Promise<Response>

Send an HTTP request over WebSocket. Returns a standard Response object.

Example:

// GET request
const response = await client.fetch('/api/users');
const users = await response.json();

// POST request
const response = await client.fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Bob' })
});

// With all fetch options
const response = await client.fetch('/api/data', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token'
  },
  body: JSON.stringify({ value: 42 })
});

subscribe

client.subscribe(pattern: string, handler: (event: PushEvent, params: Record<string, string>) => void): void

Subscribe to server push events using pica-route patterns.

Pattern Syntax:

  • /exact/path - Exact match
  • /users/:id - Match with parameter
  • /events/* - Wildcard (matches anything under /events/)
  • /users/:id/posts/:postId - Multiple parameters

Example:

// Exact match
client.subscribe('/notifications/alert', (event) => {
  console.log('Alert:', new TextDecoder().decode(event.data));
});

// With parameters
client.subscribe('/users/:userId/update', (event, params) => {
  console.log(`User ${params.userId} updated`);
});

// Wildcard
client.subscribe('/events/*', (event) => {
  console.log('Event:', event.route);
});

// Complex patterns
client.subscribe('/rooms/:roomId/messages/:msgId', (event, params) => {
  console.log(`Room: ${params.roomId}, Message: ${params.msgId}`);
});

PushEvent:

interface PushEvent {
  route: string;      // The event route
  data: Uint8Array;   // The event payload
}

unsubscribe

client.unsubscribe(pattern: string): void

Remove a subscription pattern.

Example:

client.unsubscribe('/notifications/alert');

close

client.close(): void

Close the WebSocket connection and disable auto-reconnect.

Example:

client.close();

Properties

connected

const isConnected: boolean = client.connected

Check if the WebSocket is currently connected.

Example:

if (client.connected) {
  console.log('Connected to server');
}

Usage Examples

React Example

import { useEffect, useState } from 'react';
import { WsClient } from 'gin-websocket-client';

function App() {
  const [client] = useState(() => new WsClient('ws://localhost:8080/ws'));
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // Subscribe to user events
    client.subscribe('/events/user/*', (event) => {
      fetchUsers();
    });

    fetchUsers();

    return () => client.close();
  }, []);

  const fetchUsers = async () => {
    const response = await client.fetch('/api/users');
    const data = await response.json();
    setUsers(data.users);
  };

  const createUser = async (name: string) => {
    await client.fetch('/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name })
    });
  };

  return (
    <div>
      <ul>
        {users.map(user => <li key={user.id}>{user.name}</li>)}
      </ul>
      <button onClick={() => createUser('New User')}>Add User</button>
    </div>
  );
}

Vue Example

import { ref, onMounted, onUnmounted } from 'vue';
import { WsClient } from 'gin-websocket-client';

export default {
  setup() {
    const client = new WsClient('ws://localhost:8080/ws');
    const messages = ref([]);

    onMounted(() => {
      client.subscribe('/messages/:roomId', (event, params) => {
        const msg = JSON.parse(new TextDecoder().decode(event.data));
        messages.value.push(msg);
      });
    });

    onUnmounted(() => {
      client.close();
    });

    const sendMessage = async (text: string) => {
      await client.fetch('/api/messages', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text })
      });
    };

    return { messages, sendMessage };
  }
};

Vanilla JavaScript Example

import { WsClient } from 'gin-websocket-client';

const client = new WsClient('ws://localhost:8080/ws');

// Handle notifications
client.subscribe('/notifications/:type', (event, params) => {
  const notification = new TextDecoder().decode(event.data);
  showNotification(params.type, notification);
});

// Load data
async function loadUsers() {
  const response = await client.fetch('/api/users');
  const data = await response.json();
  displayUsers(data.users);
}

// Create user
document.getElementById('createBtn').addEventListener('click', async () => {
  const name = document.getElementById('nameInput').value;

  const response = await client.fetch('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name })
  });

  if (response.ok) {
    console.log('User created!');
  }
});

loadUsers();

Protocol

This client implements the gin-websocket binary protocol:

  • Version: 0x01
  • Message Types:
    • 0x01: HTTP Request
    • 0x02: HTTP Response
    • 0x03: Server Push

All messages use big-endian byte order with length-prefixed strings.

License

MIT License

Links