Back to Documentation

API Reference

Complete reference for all classes, methods, interfaces, and configuration options in Reliable Queue.

ReliableQueue Class

The main queue class that provides reliable task processing with retry logic, status tracking, and event subscriptions.

Basic Usage

ReliableQueue Example
typescript
import { ReliableQueue, TaskStatus } from '@aplanka/reliable-queue';
// Create a queue with configuration
const queue = new ReliableQueue({
maxRetries: 3,
retryDelay: 1000,
exponentialBackoff: true,
concurrency: 2,
persistent: true
});
// Set up task processor
queue.setProcessor(async (data, task) => {
console.log('Processing task:', task.id, data);
await processYourTask(data);
});
// Add tasks
const taskId = queue.add({
message: 'Hello World'
}, {
priority: 10,
delay: 5000
});
// Subscribe to events
queue.on('taskCompleted', (task) => {
console.log('Task completed:', task.id);
});
// Get stats and manage tasks
const stats = queue.getStats();
queue.retry('task-id');
queue.clearCompleted();

Methods

constructor

constructor(config?: QueueConfig)

ReliableQueue<T>

Creates a new ReliableQueue instance with optional configuration.

constructor example
typescript
const queue = new ReliableQueue({
maxRetries: 5,
concurrency: 2
});

setProcessor

setProcessor(processor: TaskProcessor<T>): void

void

Sets the function that will process tasks in the queue.

setProcessor example
typescript
queue.setProcessor(async (data, task) => {
await processTask(data);
});

add

add(data: T, options?: AddTaskOptions): string

string - Task ID

Adds a new task to the queue and returns the task ID.

add example
typescript
const taskId = queue.add(
{ message: 'Hello' },
{ priority: 10, delay: 1000 }
);

remove

remove(taskId: string): boolean

boolean - Success status

Removes a task from the queue. Cannot remove processing tasks.

remove example
typescript
const removed = queue.remove('task-123');

retry

retry(taskId: string): boolean

boolean - Success status

Retries a failed task by resetting its status to pending.

retry example
typescript
const retried = queue.retry('failed-task-123');

retryAll

retryAll(): number

number - Number of tasks retried

Retries all failed tasks in the queue.

retryAll example
typescript
const retriedCount = queue.retryAll();

clear

clear(): void

void

Removes all tasks except those currently processing.

clear example
typescript
queue.clear();

clearCompleted

clearCompleted(): number

number - Number of tasks cleared

Removes all completed tasks from the queue.

clearCompleted example
typescript
const cleared = queue.clearCompleted();

clearFailed

clearFailed(): number

number - Number of tasks cleared

Removes all failed tasks from the queue.

clearFailed example
typescript
const cleared = queue.clearFailed();

getTasks

getTasks(): QueuedTask<T>[]

QueuedTask<T>[]

Returns a copy of all tasks in the queue.

getTasks example
typescript
const allTasks = queue.getTasks();

getTask

getTask(taskId: string): QueuedTask<T> | undefined

QueuedTask<T> | undefined

Returns a specific task by its ID.

getTask example
typescript
const task = queue.getTask('task-123');

getStats

getStats(): QueueStats

QueueStats

Returns statistics about the queue.

getStats example
typescript
const stats = queue.getStats();
console.log(`Pending: ${stats.pending}`);

on

on<K extends keyof QueueEvents<T>>(event: K, callback: QueueEvents<T>[K]): () => void

function - Unsubscribe function

Subscribes to queue events and returns an unsubscribe function.

on example
typescript
const unsubscribe = queue.on('taskCompleted', (task) => {
console.log('Task done:', task.id);
});
// Later: unsubscribe();

QueueManager Class

Singleton class for managing multiple named queues across your application.

QueueManager Example
typescript
import { QueueManager } from '@aplanka/reliable-queue';
// Get singleton instance
const manager = QueueManager.getInstance();
// Create named queues
const emailQueue = manager.createQueue('emails', {
maxRetries: 5,
concurrency: 3
});
const imageQueue = manager.createQueue('images', {
maxRetries: 2,
concurrency: 1
});
// Get existing queue
const existingQueue = manager.getQueue('emails');

getInstance()

Returns the singleton QueueManager instance.

Returns: QueueManager

createQueue(name, config)

Creates or returns an existing named queue.

Returns: ReliableQueue<T>

getQueue(name)

Gets an existing queue by name.

Returns: ReliableQueue<T> | undefined

removeQueue(name)

Removes a named queue from the manager.

Returns: boolean

Interfaces & Types

TypeScript interfaces and types used throughout the Reliable Queue library.

TypeScript Usage

Type-safe Queue Usage
typescript
import { QueuedTask, TaskStatus, QueueStats } from '@aplanka/reliable-queue';
// Task interface
interface MyTask {
userId: string;
action: 'send-email' | 'process-image';
payload: any;
}
// Create typed queue
const typedQueue = new ReliableQueue<MyTask>({
maxRetries: 3
});
// Type-safe processor
typedQueue.setProcessor(async (data: MyTask, task: QueuedTask<MyTask>) => {
switch (data.action) {
case 'send-email':
await sendEmail(data.payload);
break;
case 'process-image':
await processImage(data.payload);
break;
}
});

QueueConfig

Configuration options for the queue

maxRetries?

Maximum retry attempts (default: 3)

number

retryDelay?

Base retry delay in ms (default: 1000)

number

exponentialBackoff?

Use exponential backoff (default: true)

boolean

maxRetryDelay?

Maximum retry delay in ms (default: 30000)

number

concurrency?

Maximum concurrent tasks (default: 1)

number

persistent?

Persist to localStorage (default: false)

boolean

storageKey?

Storage key for persistence (default: "reliable-queue")

string

QueuedTask<T>

A task in the queue with metadata

id

Unique task identifier

string

data

The task payload

T

status

Current task status

TaskStatus

retryCount

Number of retry attempts

number

createdAt

Creation timestamp

number

updatedAt

Last update timestamp

number

error?

Error message if failed

string

priority?

Task priority (higher = first)

number

delay?

Processing delay in ms

number

processAt?

Scheduled processing time

number

TaskProcessor<T>

Function type for processing tasks

data

Task data to process

T

task

Complete task object

QueuedTask<T>

returns

Async function returning void

Promise<void>

QueueStats

Statistics about the queue state

total

Total number of tasks

number

pending

Tasks waiting to process

number

processing

Tasks currently processing

number

completed

Successfully completed tasks

number

failed

Failed tasks

number

AddTaskOptions

Options for adding tasks to the queue

priority?

Task priority (higher number = higher priority)

number

delay?

Delay before processing in milliseconds

number

id?

Custom task ID (auto-generated if not provided)

string

TaskStatus Enum

TaskStatus

Enumeration of possible task states

PENDING

Task is waiting to be processed

'pending'
PROCESSING

Task is currently being processed

'processing'
COMPLETED

Task completed successfully

'completed'
FAILED

Task failed after all retry attempts

'failed'

Events

Queue events allow you to respond to changes in task and queue state.

taskAdded

Event

(task: QueuedTask<T>) => void

Fired when a new task is added to the queue.

taskStarted

Event

(task: QueuedTask<T>) => void

Fired when a task begins processing.

taskCompleted

Event

(task: QueuedTask<T>) => void

Fired when a task completes successfully.

taskFailed

Event

(task: QueuedTask<T>, error: Error) => void

Fired when a task fails and exhausts all retries.

taskRetried

Event

(task: QueuedTask<T>) => void

Fired when a task is retried (either manually or automatically).

queueUpdated

Event

(tasks: QueuedTask<T>[]) => void

Fired whenever the queue state changes.

Utility Functions

Exported utility functions that can be used independently.

generateId()

Generates a unique identifier for tasks.

Returns: string

calculateRetryDelay()

Calculates retry delay with exponential backoff.

Returns: number

sleep(ms)

Promise-based sleep utility.

Returns: Promise<void>

isBrowser()

Detects if running in browser environment.

Returns: boolean

Next Steps

Now that you understand the API, explore other documentation sections to learn more about specific topics.