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

sse-client-web

v1.8.0

Published

Use Server Send Event by subscribe style

Downloads

4

Readme

sse-client-web

A easier way to use Server Sent Events in subscribe style in Web / Node.js.

Why?

Compared to normal HTTP request, there are fewer libraries available for SSE (Server Sent Events).

As an axios user, I'm looking for a way to use SSE as I did with axios.

This package makes your work slightly easier.

Installation

npm install sse-client-web -S

Then with a module bundler like rollup or webpack, use as you would anything else:

// using ES6 modules
import { SSEClient } from 'sse-client-web'

// using CommonJS modules
var { SSEClient } = require('sse-client-web')

The UMD build is also available on unpkg:

<script src="https://unpkg.com/[email protected]/lib/index.browser.js"></script>

You can find the library on window.SSEClient.

Usage

import { SSEClient } from 'sse-client-web'

// subscribe from URL
const client = new SSEClient({
  baseURL: '/sse'
})

client.onError((url, event) => {
  console.log(url, event)
})

const subscriber = client.subscribe('/real-time-events')
  .on('event1', data => {
    /** your codes here */
  })
  .on('event2', data => {
    /** your codes here */
  })
  .on('*', data => {
    /** your codes here */
  })

// ...

// unsubscribe events
subscriber.off('event1')
subscriber.off('event2')
// or unsubscribe all events
subscriber.offAll()

Typescript

Use Typescript to import type inference for SSEClient instance method.

import { SSEClient } from 'sse-client-web'

type MySSEClient = {
  '/real-time-events': {
    foo: string
    bar: number
  }
}

// subscribe from URL
const client = new SSEClient<MySSEClient>({
  baseURL: '/sse'
})

client.onError((url, event) => {
  console.log(url, event)
})

client.subscribe('/it-doesnt-exist') // Error: Argument of type 'it-doesnt-exist' is not assignable to parameter of type 'foo' | 'bar'

const subscriber = client.subscribe('/real-time-events')
  .on('foo', data => {
    /** your codes here */
  })
  .on('bar', data => {
    /** your codes here */
  })
  .on('fox', data => { }) // Error: Property 'fox' does not exist on type

// ...

API

SSEClient{}

A class to create SSEClient instance.

  • Type
export declare class SSEClient<Events extends Record<string, SSEClientSubscriberType>> {
    constructor(config?: SSEClientConfig, interceptor?: SSEClientInterceptor<keyof Events>);
    subscribe<Url extends keyof Events = ''>(url: Url): SSEEventSubscriber<Events[Url]>;
    unsubscribe<Url extends keyof Events>(url: Url): void;
    onError(onErrorComing: ErrorHandler<keyof Events>): void;
}
  • Example
// subscribe from URL
const client = new SSEClient({
  baseURL: '/sse',
  retry: {
    // ms, default is 1000
    interval: 2000,
    // default is 3
    retries: 5
  }
})

SSEClient.subscribe()

  • Type
// Events[Url] === SSEClientSubscriberType
subscribe<Url extends keyof Events>(
  url: Url
): SSEEventSubscriber<Events[Url]>
  • Example
const subscriber = new SSEClient()
  .subscribe('/real-time-events')

SSEClient.unsubscribe()

  • Type
unsubscribe<Url extends keyof Events>(
  url: Url
): void
  • Example
const client = new SSEClient()
client.subscribe('/real-time-events')
// ...
client.unsubscribe('/real-time-events')

SSEEventSubscriber{}

A class to create SSEEventSubscriber instance, which manages event listening.

  • Type
export declare class SSEEventSubscriber<Events extends SSEClientSubscriberType> {
    constructor(event: EventSource, url?: string, interceptor?: SSEClientInterceptor<string>);
    /**
     * register event
     * @param event event in `MessageEvent`, use `'*'` to receive unnamed event.
     * @param onMessageComing
     */
    on<EventName extends keyof Events>(event: EventName | '*', onMessageComing: ComingMessageHandler<Events[EventName]>): this;
    /**
     * unregister event
     */
    off<EventName extends keyof Events>(event: EventName): this;
    /**
     * unregister all events
     */
    offAll(): void;
    /**
     * re-register all binding events
     */
    reRegister(): void;
    /**
     * waiting for event source connection established
     */
    waitUntilOpened(): Promise<unknown>;
}

SSEEventSubscriber.on()

Listen a specified type of event.

  • Type
on<EventName extends keyof Events>(
  event: EventName | '*',
  onMessageComing: ComingMessageHandler<Events[EventName]>
): this;
  • Example
const subscriber = new SSEClient()
  .subscribe('/real-time-events')
    .on('foo', data => {
      // ...
    })

SSEEventSubscriber.off()

Cancel listening a specified type of event.

  • Type
off<EventName extends keyof Events>(
  event: EventName
): this;
  • Example
const subscriber = new SSEClient()
  .subscribe('/real-time-events')
    .off('foo')

SSEEventSubscriber.offAll()

Cancel listening ALL types of event.

  • Type
offAll(): void

SSEEventSubscriber.waitUntilOpened()

Waiting for event source connection established

  • Type
waitUntilOpened(): Promise<unknown>
  • Example
const subscriber = new SSEClient()
  .subscribe('/real-time-events')

await subscriber.waitUntilOpened()
console.log('connection established.')

License

MIT License © 2023 MeetinaXD