0.0.2 • Published 7 months ago
@antei/tasks v0.0.2
@antei/tasks
A robust, type-safe, and easy-to-use task queue system built on BullMQ, designed for Node.js and Bun environments. It simplifies background job processing with zero-config defaults, Dragonfly support, and optional database persistence.
Features
- 🚀 Zero Configuration: Defaults to local Redis.
- ✅ Type Safety: Zod schema validation & TypeScript.
- 💾 Optional Persistence: Built-in support for Postgres, MySQL, SQLite.
- 🐉 Dragonfly Optimized: Works efficiently with DragonflyDB.
- 👂 Event Listeners: Hook into job lifecycle events.
- 🔄 Smart Retries: Configurable backoff strategies.
- 📊 Queue Management: Global access to jobs and metrics via
tasks.
Installation
npm install @antei/tasks bullmq
# or
bun install @antei/tasks bullmqNote: bullmq is a peer dependency and must be installed alongside @antei/tasks.
For Database Persistence (Optional):
You also need knex and a database driver if using the persistence feature.
# Install Knex
npm install knex --save-optional
# Install DB driver (e.g., PostgreSQL)
npm install pg --save-optionalSee Persistence Docs for details.
Getting Started
import { task, configure, tasks } from '@antei/tasks';
import { z } from 'zod';
// Optional: Configure Redis connection if not using localhost:6379
// configure({
// redis: { host: 'redis.example.com', port: 6379 },
// });
// 1. Define your task
const sendWelcomeEmail = task({
queueName: 'emails',
schema: z.object({
userId: z.string().uuid(),
email: z.string().email(),
}),
executor: async ({ payload, progress }) => {
console.log(`Sending welcome email to ${payload.email}`);
await progress(50);
// ... send email logic ...
await new Promise((resolve) => setTimeout(resolve, 500));
await progress(100);
console.log(`Email sent to ${payload.userId}`);
return { success: true };
},
});
// 2. Add jobs to the queue
async function main() {
const job1 = await sendWelcomeEmail.add({
userId: 'a1b2c3d4-e5f6-7890-1234-567890abcdef',
email: 'alice@example.com',
});
console.log(`Queued job ${job1.id}`);
const job2 = await sendWelcomeEmail.add(
{
userId: 'f0e9d8c7-b6a5-4321-fedc-ba9876543210',
email: 'bob@example.com',
},
{ delay: 5000 }
); // Delay this job by 5 seconds
console.log(`Queued delayed job ${job2.id}`);
// 3. Wait for processing (in a real app, workers run continuously)
await new Promise((resolve) => setTimeout(resolve, 10000));
// 4. Optionally check status or metrics globally
const metrics = await tasks.getMetrics('emails');
console.log('Email Queue Metrics:', metrics);
// 5. Clean up resources (important for graceful shutdown)
await sendWelcomeEmail.close();
}
main().catch(console.error);Learn More
Dive deeper into specific features:
- Task Persistence: Storing task state in SQL databases.
- Event Listeners: Reacting to job lifecycle events.
- Advanced Usage: Cross-queue management, task options, Dragonfly, custom plugins.
- API Reference: Detailed function and type signatures.
License
MIT