0.0.2 • Published 1 year ago

polling-connection v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

polling-connection

build downloads npm

Event-based polling module written in TS with time tracking and aborting support.

:white_check_mark: Agnostic (works with axios, fetch or any async function) :white_check_mark: Written in TypeScript :white_check_mark: Time tracking :white_check_mark: Abort signal support

installation

NPM:

npm install polling-connection

Yarn:

yarn add polling-connection

examples

usage

Create a new connection:

import { polling } from "polling-connection";

const connection = polling({
  task: async ({ done, signal }) => {
    const response = await axios.get("user/status", { signal });
    if (response.data.status === 1) {
      done(response.data);
    }
  },
  timeout: 30000,
  delay: 3000,
});

Listen to the events:

connection.on("success", (data) => {
  console.log(data);
  console.log("The connection is automatically closed on success");
});

connection.on("timeout", () => {
  console.log("Connection is automatically closed on timeout");
});

connnection.on("second", ({ passed, remaining }) => {
  console.log("seconds passed:", passed);
  console.log("seconds remamining:", remaining);
});

connection.on("error", (err) => {
  console.error(err);
  console.log("The connection is still active");
});

connection.on("close", () => {
  console.log("The connection is closed");
});

Start the polling:

connection.start();

Manually close the connection:

connection.close();

Clear all event listeners:

connection.removeAllEventListeners();

Close connection and remove all event listeners:

connection.destroy();

api

polling(options: PollingOptions) => PollingConnection

Creates a new polling connection.

Available options:

OptionDescriptionDefault
taskAn async function that will be executed while the connection is openRequired
delayDelay in milliseconds after each call3000 (3 seconds)
timeoutTime in milliseconds for timeout30000 (30 seconds)

Example:

const connection = polling<ResultType>({
  task: async ({ done, signal }) => {
    const result = await someAsyncTask({ signal });
    if (result === "ok") {
      done(result);
    }
  },
});

The connection instance provides the following methods:

start() => void

Starts the connection and executes the task until it reaches the timeout or the connection is closed (either by success or manually closed)

Before calling this method you must add the event listeners.

Example:

connection.start();

on(event: PollingEvent, data) => Unsubscribe

Adds a new event listener.

Supported events:

EventDescriptionArguments
startWhen the connection is started{passed: number; remaining: number}
successWhen the done callback is called. The connection is also automatically closed, which means that the close event will also be called after successThe payload given to done callback
errorWhen the task throws an exception. This does not closes the connection.err: unknown
timeoutWhen the polling reaches the timeout. This closes the event, which means the close event are also triggered after this event.None
secondWhen a second passes while the polling is active. The arguments are the passed and remaining time in seconds.{passed: number; remaining: number}
closeWhen the connection is closed either my manualling calling the close or destroy events, or when the polling reaches the timeoutNone

Example:

connection.on("start", () => {
  console.log("The connection is started");
});

connection.on("success", (data) => {
  console.log("done called with:", data);
});

connection.on("second", ({ passed, remaining }) => {
  console.log("seconds passed:", passed);
  console.log("seconds remaining:", remaining);
});

connection.on("error", (err) => {
  console.log("thrown exception:", err);
  console.log("...but the polling is still active");

  // Depending on the error you can close the connection
  if (isBadError(err)) {
    connection.close();
  }
});

connection.on("timeout", () => {
  console.log("polling reached the timeout");
  console.log("the polling will be closed and trigger the `close` event");
});

console.log("close", () => {
  console.log("the polling is closed");
});

This method also return the unsubscribe function:

const unsubscribe = connection("success", handleSuccess);

// ...

unsubscribe(); // remove the success listener

close() => void

Closes the connection.

removeAllEventListeners() => void

Removes all the event listeners.

destroy() => void

Closes the connection and remove all the event listeners.

license

MIT