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.

river.ts's People

Contributors

bewinxed avatar

Stargazers

NguyenBaKhiem avatar Mark Wilkins avatar apeman avatar Matt Burton avatar Askar Yusupov avatar Oleg Bochagov avatar  avatar Ali Torki avatar Will Ruggiano avatar Andrejs Agejevs avatar Shayon avatar Sean Lynch avatar Zafar Ansari avatar GStudiosX avatar Mathew Chan avatar JP Camara avatar βŠ£Λšβˆ†ΛšβŠ’ avatar Dale Inverarity avatar gsemy avatar Zachary avatar EA avatar Danovan avatar Chendong Xie avatar K.K. avatar ZhengWei avatar Ruslan Konviser avatar icantunderstand avatar Franz Fletcher avatar monkeytao avatar Hendry Sadrak avatar Ann avatar lenq avatar Carl Brugger avatar Karan Garg avatar sugar avatar  avatar lushiqiang avatar Teerapat Prommarak avatar Cristian Hernandez avatar Jakub Ε»ywiec avatar HervΓ© Tutuaku avatar Ozabra avatar Samuel avatar Johana Mburu avatar Chris Ellis avatar Junsuk Park avatar Simon Babay avatar  avatar Bernard avatar  avatar

Watchers

Cristian Hernandez avatar  avatar

river.ts's Issues

A good lib for SSE

i have read the source code. i think the design of steam function in server is a good pattern. it use callback to connect each other.

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.