express-long-polling
Version:
Library to implement task dispatching with long-polling approach on express server.
74 lines (73 loc) • 2.71 kB
TypeScript
import type { Request } from 'express';
export declare class LongPollingTask<Input, Output> {
readonly id: string;
readonly input: Input;
protected listeners: Array<(output: Output) => void>;
constructor(id: string, input: Input);
toJSON(): {
id: string;
input: Input;
};
dispatchResult(output: Output): void;
addListener(listener: (output: Output) => void): void;
removeListener(listener: (output: Output) => void): void;
}
/** @description redirect with 307 to let client retry */
declare function defaultOnTimeout(req: Request): void;
export declare class LongPollingTaskQueue<Input, Output, Task extends LongPollingTask<Input, Output> = LongPollingTask<Input, Output>> {
protected pollingInterval: number;
/**
* @description list of pending request from workers
*/
protected pendingTaskListeners: Array<(task: Task) => void>;
/**
* @description list of pending tasks for workers that are not completed
*/
protected pendingTasks: Task[];
/**
* @description list of all tasks for client, both completed or not completed tasks.
*/
protected allTasks: Record<string, Task>;
constructor(options?: {
/** @default 30 seconds */
pollingInterval?: number;
});
/**
* @description create task from client
*/
addTask(options: {
/** @default randomUUID */
id?: string | (() => string);
input: Input;
}): {
id: string;
};
protected getFirstTask(): Task | null;
protected getRandomTask(): Task | null;
protected popTaskById(id: string): Task | null;
protected waitTask(req: Request, onTask: (task: Task) => void, onTimeout?: typeof defaultOnTimeout): void;
/**
* @description get task from worker
*/
getOrWaitTask(getTask: 'first' | 'random', req: Request, onTask: (task: {
id: string;
input: Input;
}) => void, onTimeout?: typeof defaultOnTimeout): void;
/**
* @description dispatch result from worker
* @returns true if the task is found and deleted
* @returns false if the task is not found (maybe already deleted)
*/
dispatchResult(id: string, output: Output): boolean;
/**
* @description get result from client (dispatched from worker)
*/
getOrWaitResult(id: string, req: Request, onOutput: (output: Output) => void, onTimeout?: typeof defaultOnTimeout): void;
/**
* @description delete completed task from client (to release memory)
* @returns true if the task is found and deleted
* @returns false if the task is not found (maybe already deleted)
*/
deleteTask(id: string): boolean;
}
export {};