Coder Social home page Coder Social logo

river.ts's Introduction

00171-1636846244

๐ŸŒŠ river.ts | โœจ Composable, Typesafe SSE Events

License TypeScript npm

river.ts is a powerful library for handling server-sent events (SSE) in TypeScript. It allows you to build a common interface for events, then use it consistently on both server and client sides. Compatible with express-like backends and modern frontend frameworks.

๐ŸŒŸ Features

  • ๐Ÿ’ก Easy-to-use API for defining, emitting, and handling events
  • ๐Ÿ”„ Automatic reconnection with configurable options
  • ๐Ÿ”Œ Works with various HTTP methods and supports custom headers, body, etc.
  • ๐Ÿ› ๏ธ Type-safe event handlers and payload definitions
  • ๐Ÿš€ Streamlined setup for both server and client sides

๐Ÿ“ฆ Installation

npm install river.ts
# or
yarn add river.ts
# or
pnpm add river.ts
# or
bun add river.ts

๐Ÿš€ Usage

๐Ÿ— Define your event map

Use the RiverEvents class to define your event structure:

import { RiverEvents } from 'river.ts';

const events = new RiverEvents()
  .defineEvent('ping', {
    message: 'pong'
  })
  .defineEvent('payload', {
    data: [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' }
    ],
    stream: true
  })
  .build();

๐ŸŒ  On the Server

Use RiverEmitter to set up the server-side event emitter:

import { RiverEmitter } from 'river.ts/server';
import { events } from './events';

const emitter = RiverEmitter.init(events);

function handleSSE(req: Request, res: Response) {
  const stream = emitter.stream({
    callback: async (emit) => {
      await emit('ping', { message: 'pong' });
      await emit('payload', {
        data: [
          { id: 1, name: 'Alice' },
          { id: 2, name: 'Bob' }
        ]
      });
    },
    clientId: '...', // optional param to set a custom client ID
    ondisconnect: (clientId) => {
      // optional param to handle disconnections
    }
  });

  return new Response(stream, {
    headers: emitter.headers()
  });
}

๐Ÿš€ On the Client

Use RiverClient to set up the client-side event listener:

import { RiverClient } from 'river.ts/client';
import { events } from './events';

const client = RiverClient.init(events);

client
  .prepare('http://localhost:3000/events', {
    method: 'GET',
    headers: {
      // Add any custom headers here
    }
  })
  .on('ping', (data) => {
    console.log('Ping received:', data.message);
  })
  .on('payload', (data) => {
    console.log('Payload received:', data);
  })
  .stream();

๐Ÿ” Type Safety

Leverage TypeScript's type system for type-safe event handling:

import { InferEventType } from 'river.ts';

type Events = typeof events;
type PingEvent = InferEventType<Events, 'ping'>;
// {
//   message: string;
//   type: "ping";
// }

const pingEvents: PingEvent[] = [];
pingEvents.push({
  message: 'pong',
  type: 'ping'
});

๐ŸŽ‰ Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request.

๐Ÿ“„ License

This project is licensed under the MIT License.

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.