API Reference
Complete reference for all classes, methods, interfaces, and configuration options in Reliable Queue.
Table of Contents
ReliableQueue Class
The main queue class that provides reliable task processing with retry logic, status tracking, and event subscriptions.
Basic Usage
import { ReliableQueue, TaskStatus } from '@aplanka/reliable-queue';// Create a queue with configurationconst queue = new ReliableQueue({maxRetries: 3,retryDelay: 1000,exponentialBackoff: true,concurrency: 2,persistent: true});// Set up task processorqueue.setProcessor(async (data, task) => {console.log('Processing task:', task.id, data);await processYourTask(data);});// Add tasksconst taskId = queue.add({message: 'Hello World'}, {priority: 10,delay: 5000});// Subscribe to eventsqueue.on('taskCompleted', (task) => {console.log('Task completed:', task.id);});// Get stats and manage tasksconst stats = queue.getStats();queue.retry('task-id');queue.clearCompleted();
Methods
constructor
constructor(config?: QueueConfig)
Creates a new ReliableQueue instance with optional configuration.
const queue = new ReliableQueue({maxRetries: 5,concurrency: 2});
setProcessor
setProcessor(processor: TaskProcessor<T>): void
Sets the function that will process tasks in the queue.
queue.setProcessor(async (data, task) => {await processTask(data);});
add
add(data: T, options?: AddTaskOptions): string
Adds a new task to the queue and returns the task ID.
const taskId = queue.add({ message: 'Hello' },{ priority: 10, delay: 1000 });
remove
remove(taskId: string): boolean
Removes a task from the queue. Cannot remove processing tasks.
const removed = queue.remove('task-123');
retry
retry(taskId: string): boolean
Retries a failed task by resetting its status to pending.
const retried = queue.retry('failed-task-123');
retryAll
retryAll(): number
Retries all failed tasks in the queue.
const retriedCount = queue.retryAll();
clear
clear(): void
Removes all tasks except those currently processing.
queue.clear();
clearCompleted
clearCompleted(): number
Removes all completed tasks from the queue.
const cleared = queue.clearCompleted();
clearFailed
clearFailed(): number
Removes all failed tasks from the queue.
const cleared = queue.clearFailed();
getTasks
getTasks(): QueuedTask<T>[]
Returns a copy of all tasks in the queue.
const allTasks = queue.getTasks();
getTask
getTask(taskId: string): QueuedTask<T> | undefined
Returns a specific task by its ID.
const task = queue.getTask('task-123');
getStats
getStats(): QueueStats
Returns statistics about the queue.
const stats = queue.getStats();console.log(`Pending: ${stats.pending}`);
on
on<K extends keyof QueueEvents<T>>(event: K, callback: QueueEvents<T>[K]): () => void
Subscribes to queue events and returns an unsubscribe function.
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.
import { QueueManager } from '@aplanka/reliable-queue';// Get singleton instanceconst manager = QueueManager.getInstance();// Create named queuesconst emailQueue = manager.createQueue('emails', {maxRetries: 5,concurrency: 3});const imageQueue = manager.createQueue('images', {maxRetries: 2,concurrency: 1});// Get existing queueconst 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
import { QueuedTask, TaskStatus, QueueStats } from '@aplanka/reliable-queue';// Task interfaceinterface MyTask {userId: string;action: 'send-email' | 'process-image';payload: any;}// Create typed queueconst typedQueue = new ReliableQueue<MyTask>({maxRetries: 3});// Type-safe processortypedQueue.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)
retryDelay?
Base retry delay in ms (default: 1000)
exponentialBackoff?
Use exponential backoff (default: true)
maxRetryDelay?
Maximum retry delay in ms (default: 30000)
concurrency?
Maximum concurrent tasks (default: 1)
persistent?
Persist to localStorage (default: false)
storageKey?
Storage key for persistence (default: "reliable-queue")
QueuedTask<T>
A task in the queue with metadata
id
Unique task identifier
data
The task payload
status
Current task status
retryCount
Number of retry attempts
createdAt
Creation timestamp
updatedAt
Last update timestamp
error?
Error message if failed
priority?
Task priority (higher = first)
delay?
Processing delay in ms
processAt?
Scheduled processing time
TaskProcessor<T>
Function type for processing tasks
data
Task data to process
task
Complete task object
returns
Async function returning void
QueueStats
Statistics about the queue state
total
Total number of tasks
pending
Tasks waiting to process
processing
Tasks currently processing
completed
Successfully completed tasks
failed
Failed tasks
AddTaskOptions
Options for adding tasks to the queue
priority?
Task priority (higher number = higher priority)
delay?
Delay before processing in milliseconds
id?
Custom task ID (auto-generated if not provided)
TaskStatus Enum
TaskStatus
Enumeration of possible task states
PENDING
Task is waiting to be processed
PROCESSING
Task is currently being processed
COMPLETED
Task completed successfully
FAILED
Task failed after all retry attempts
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.