API Reference
Complete API documentation for Pidgey.
Pidgey Client
Pidgey(config)
Creates a new Pidgey client instance.
import { Pidgey } from '@pidgeyjs/next';
const pidgey = Pidgey({
adapter: 'sqlite',
filename: './pidgey.db',
});Config options:
// SQLite adapter
{
adapter: 'sqlite';
filename?: string; // Default: './pidgey.db' (use ':memory:' for in-memory)
}
// PostgreSQL adapter
{
adapter: 'postgres';
connection: string; // PostgreSQL connection string
}
// Redis adapter (powered by BullMQ)
{
adapter: 'redis';
options: {
host: string;
port?: number;
password?: string;
// Additional Redis connection options
};
}pidgey.defineJob(definition)
Defines a job and registers it with the client.
const sendEmail = pidgey.defineJob({
name: 'send-email',
handler: async (data: { to: string; subject: string }) => {
// Your job logic
return { sent: true };
},
config: {
retries: 3,
timeout: 30000,
},
});Parameters:
name— Unique identifier for this job typehandler— Async function that processes the job dataconfig(optional) — Job configuration
Config options:
retries— Max retry attempts (default: 3)timeout— Timeout in milliseconds (default: 300000 / 5 minutes)queue— Queue name (default: job name)
Returns: JobDefinition
pidgey.defineScheduledJob(definition)
Defines a scheduled job that runs on a cron schedule.
const dailyDigest = pidgey.defineScheduledJob({
name: 'daily-digest',
handler: async () => {
// Scheduled jobs have no input data
await sendDigestEmail();
return { sent: true };
},
schedule: {
cron: '0 9 * * *', // Every day at 9am
timezone: 'America/New_York',
},
});Parameters:
name— Unique identifier for this scheduled jobhandler— Async function with no parameters (void handler)schedule— Schedule configuration (required)cron— Cron expressiontimezone— IANA timezone (default: “UTC”)
config(optional) — Job configuration (retries, timeout, queue)
Returns: ScheduledJobDefinition
pidgey.enqueue(name, data, options?)
Enqueues a job by name. Prefer using the enqueue method on the job definition for type safety.
await pidgey.enqueue('send-email', {
to: 'tom.haverford@pawnee.gov',
subject: 'Hello',
});Parameters:
name— Job name (must be defined withdefineJob)data— Job data (any JSON-serializable value)options(optional) — Enqueue options
Options:
delay— Delay in milliseconds before processingmaxAttempts— Override max retry attemptstimeout— Override timeout
Returns: Promise<Job>
pidgey.getJob(id)
Retrieves a job by ID.
const job = await pidgey.getJob('job_abc123');
console.log(job.status); // 'pending' | 'active' | 'completed' | 'failed' | 'cancelled'Returns: Promise<Job | null>
pidgey.healthCheck()
Performs a detailed health check on the Pidgey client and its storage backend.
const health = await pidgey.healthCheck();
if (health.status === 'healthy') {
console.log('Pidgey is operational');
} else {
console.error('Pidgey health check failed:', health.error);
}Returns: Promise<HealthCheckResult>
interface HealthCheckResult {
status: 'healthy' | 'unhealthy';
connected: boolean;
adapter: string;
timestamp: Date;
error?: string;
}pidgey.isHealthy()
Simple boolean health check. Useful for platform health endpoints.
const healthy = await pidgey.isHealthy();
// Returns: true or falseReturns: Promise<boolean>
pidgey.cancelJob(id)
Cancels a pending job.
await pidgey.cancelJob('job_abc123');The Redis adapter does not support canceling jobs. Use deleteJob instead.
Parameters:
id— Job ID to cancel
pidgey.retryJob(id)
Retries a failed job by resetting its status to pending.
await pidgey.retryJob('job_abc123');Parameters:
id— Job ID to retry
pidgey.retryAllFailed(queue?)
Retries all failed jobs, optionally filtered by queue.
// Retry all failed jobs
const count = await pidgey.retryAllFailed();
// Retry failed jobs in a specific queue
const emailCount = await pidgey.retryAllFailed('emails');Parameters:
queue— Optional queue name to filter by
Returns: Promise<number> — Number of jobs retried
pidgey.listJobs(options?)
Lists jobs with optional filtering and pagination.
// Get all pending jobs
const pendingJobs = await pidgey.listJobs({ status: 'pending' });
// Get jobs from a specific queue with pagination
const emailJobs = await pidgey.listJobs({
queue: 'emails',
limit: 50,
offset: 0,
});Options:
queue— Filter by queue namestatus— Filter by job status ('pending'|'active'|'completed'|'failed'|'cancelled')limit— Maximum number of jobs to return (default: 100)offset— Number of jobs to skip (default: 0)
Returns: Promise<Job[]>
Job Deletion API
pidgey.deleteJob(id)
Permanently deletes a job.
await pidgey.deleteJob('job_abc123');Parameters:
id— Job ID to delete
pidgey.deleteJobs(options?)
Deletes multiple jobs matching the filter criteria.
// Delete all failed jobs
const count = await pidgey.deleteJobs({ status: 'failed' });
// Delete all jobs in a queue
const emailCount = await pidgey.deleteJobs({ queue: 'emails' });
// Delete failed jobs in a specific queue
await pidgey.deleteJobs({ status: 'failed', queue: 'emails' });Options:
status— Filter by job status ('pending'|'active'|'completed'|'failed'|'cancelled')queue— Filter by queue name
Returns: Promise<number> — Number of jobs deleted
JobDefinition
The object returned by defineJob.
jobDefinition.enqueue(data, options?)
Type-safe method to enqueue this specific job.
const job = await sendEmail.enqueue(
{ to: 'tom.haverford@pawnee.gov', subject: 'Welcome' }, // Autocomplete & type-checked
{ delay: 5000 } // Run in 5 seconds
);Parameters:
data— Job data (typed based on handler)options(optional) — Enqueue options
Options:
delay— Delay in millisecondsmaxAttempts— Override max retry attemptstimeout— Override timeout
Returns: Promise<Job>
jobDefinition.invoke(data)
Directly invokes the handler without going through the queue. Useful for testing.
const result = await sendEmail.invoke({
to: 'ron.swanson@pawnee.gov',
subject: 'Test',
});Parameters:
data— Job data (typed based on handler)
Returns: Handler return value (bypasses queue entirely)
Job
Represents an enqueued job.
interface Job {
id: string;
queue: string;
data: JsonValue;
status: 'pending' | 'active' | 'completed' | 'failed' | 'cancelled';
result?: JsonValue;
error?: string;
attempts: number;
maxAttempts: number;
startedAt?: Date;
runAt: Date;
completedAt?: Date;
createdAt: Date;
updatedAt: Date;
}Fields:
id— Unique job ID (prefixed withjob_)queue— Queue name for this jobdata— Job payloadstatus— Current job statusresult— Handler return value (only set if completed)error— Error message (only set if failed)attempts— Number of execution attemptsmaxAttempts— Max allowed attemptsstartedAt— When job execution startedrunAt— When job should run (considers delays)completedAt— When job finished (success or failure)createdAt— When job was createdupdatedAt— When job was last updated
Type Utilities
JsonValue
Type representing JSON-serializable values:
type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };Use this to type job data and results.
Type Inference
Pidgey infers types from your job definitions:
const myJob = pidgey.defineJob({
name: 'my-job',
handler: async (data: { userId: number }) => {
return { success: true, timestamp: Date.now() };
},
});
// TypeScript knows the exact types
await myJob.enqueue({ userId: 123 }); // ✅ Typed
await myJob.enqueue({ userId: 'abc' }); // ❌ Type error
const result = await myJob.invoke({ userId: 123 });
result.success; // ✅ boolean
result.timestamp; // ✅ numberScheduled Jobs API
pidgey.syncSchedules()
Manually synchronizes scheduled jobs with the database.
The worker automatically syncs schedules on startup. This method is only needed if you want to sync from your application process.
await pidgey.syncSchedules();pidgey.listScheduledJobs()
Lists all scheduled jobs.
const schedules = await pidgey.listScheduledJobs();Returns: Promise<ScheduledJob[]>
pidgey.getScheduledJob(name)
Gets a scheduled job by name.
const schedule = await pidgey.getScheduledJob('daily-digest');Returns: Promise<ScheduledJob | null>
pidgey.pauseScheduledJob(name)
Pauses a scheduled job.
await pidgey.pauseScheduledJob('daily-digest');pidgey.resumeScheduledJob(name)
Resumes a paused scheduled job.
await pidgey.resumeScheduledJob('daily-digest');pidgey.deleteScheduledJob(name)
Deletes a scheduled job.
await pidgey.deleteScheduledJob('daily-digest');ScheduledJob
interface ScheduledJob {
id: string;
name: string;
queue: string;
cron: string;
timezone: string;
data: JsonValue;
paused: boolean;
lastRunAt: Date | null;
nextRunAt: Date | null;
createdAt: Date;
updatedAt: Date;
}Next Steps
- Jobs — Core job features (delays, retries, DLQ)
- Scheduled Jobs — Cron-based recurring jobs
- Guides — Real-world examples
- CLI — Command-line reference