npm package: @haykal/jobs-backend
Description: > Background job processing with BullMQ — queue management, job scheduling, health monitoring, and an admin API for queue inspection.
Latest version: 1.0.0

# @haykal/jobs-backend

> Background job processing with BullMQ — queue management, job scheduling, health monitoring, and an admin API for queue inspection.

## Installation

```bash
pnpm add @haykal/jobs-backend
```

## Configuration

### `forRoot()` Options

```typescript
import { JobsModule } from '@haykal/jobs-backend';

@Module({
  imports: [
    JobsModule.forRoot({
      redis: {
        host: 'localhost',
        port: 6379,
        password: undefined,
        db: 0,
      },
      queues: ['email', 'notifications', 'reports'],
      defaultJobOptions: {
        attempts: 3,
        backoff: { type: 'exponential', delay: 1000 },
        removeOnComplete: 100,
        removeOnFail: 500,
      },
      dashboard: {
        enabled: true,
        basePath: '/admin/jobs',
      },
      workers: {
        concurrency: 5,
      },
    }),
  ],
})
export class AppModule {}
```

### Configuration Reference

| Property                             | Type                | Required | Default         | Description                                 |
| ------------------------------------ | ------------------- | -------- | --------------- | ------------------------------------------- |
| `redis.host`                         | `string`            | **Yes**  | —               | Redis host                                  |
| `redis.port`                         | `number`            | **Yes**  | —               | Redis port                                  |
| `redis.password`                     | `string`            | No       | —               | Redis password                              |
| `redis.db`                           | `number`            | No       | `0`             | Redis database number                       |
| `queues`                             | `string[]`          | **Yes**  | —               | Queue names to auto-register                |
| `defaultJobOptions.attempts`         | `number`            | No       | —               | Default retry attempts                      |
| `defaultJobOptions.backoff`          | `object`            | No       | —               | `{ type: 'fixed' \| 'exponential', delay }` |
| `defaultJobOptions.priority`         | `number`            | No       | —               | Job priority (lower = higher)               |
| `defaultJobOptions.removeOnComplete` | `boolean \| number` | No       | —               | Auto-remove completed jobs                  |
| `defaultJobOptions.removeOnFail`     | `boolean \| number` | No       | —               | Auto-remove failed jobs                     |
| `defaultJobOptions.timeout`          | `number`            | No       | —               | Job timeout in ms                           |
| `dashboard.enabled`                  | `boolean`           | No       | `false`         | Enable admin API endpoints                  |
| `dashboard.basePath`                 | `string`            | No       | `'/admin/jobs'` | Dashboard base path                         |
| `workers.concurrency`                | `number`            | No       | `5`             | Worker concurrency per queue                |

## Key Exports

| Export                | Type          | Description                                           |
| --------------------- | ------------- | ----------------------------------------------------- |
| `JobsModule`          | NestJS Module | Global module with `forRoot()` / `forRootAsync()`     |
| `JOBS_CONFIG`         | Symbol        | Inject the config object                              |
| `JOBS_QUEUES`         | Symbol        | Inject the `Map<string, Queue>` of registered queues  |
| `JobsService`         | Service       | Enqueue jobs, schedule recurring, manage queues       |
| `JobsHealthIndicator` | Service       | Health check for all queues                           |
| `JobsAdminController` | Controller    | Queue inspection and control (when dashboard enabled) |

## API Endpoints

Enabled when `dashboard.enabled: true`. Base path: `/api/jobs`.

| Method   | Path                           | Description                      |
| -------- | ------------------------------ | -------------------------------- |
| `GET`    | `/jobs/queues`                 | List all queues with stats       |
| `GET`    | `/jobs/queues/:name`           | Get queue details                |
| `GET`    | `/jobs/queues/:name/jobs`      | List jobs (filterable by status) |
| `GET`    | `/jobs/queues/:name/jobs/:id`  | Get job details                  |
| `POST`   | `/jobs/queues/:name/retry-all` | Retry all failed jobs            |
| `DELETE` | `/jobs/queues/:name/clean`     | Clean completed/failed jobs      |
| `POST`   | `/jobs/queues/:name/pause`     | Pause a queue                    |
| `POST`   | `/jobs/queues/:name/resume`    | Resume a paused queue            |

## Usage Examples

### Enqueueing a Job

```typescript
import { JobsService } from '@haykal/jobs-backend';

@Injectable()
export class EmailService {
  constructor(private readonly jobs: JobsService) {}

  async sendWelcomeEmail(userId: string, email: string) {
    await this.jobs.enqueue('email', 'welcome', { userId, email });
  }
}
```

### Scheduling a Recurring Job

```typescript
await this.jobs.scheduleRecurring('reports', 'daily-summary', {
  pattern: '0 8 * * *', // 8 AM daily
  data: { type: 'daily' },
});
```

### Delayed Job

```typescript
await this.jobs.enqueueDelayed(
  'notifications',
  'reminder',
  {
    userId,
    message: "Don't forget!",
  },
  60 * 60 * 1000,
); // 1 hour delay
```

### Health Check

```typescript
import { JobsHealthIndicator } from '@haykal/jobs-backend';

@Controller('health')
export class HealthController {
  constructor(private readonly jobsHealth: JobsHealthIndicator) {}

  @Get()
  async check() {
    return this.jobsHealth.check();
  }
}
```

## Related Packages

- `@haykal/jobs-client` — React Query hooks for queue dashboard
- `@haykal/core-backend` — Base infrastructure
- `@haykal/email-backend` — Uses jobs for email queue delivery

## Further Reading

- [API Reference](../../../docs/api-reference.md) — Full endpoint listing
- [Architecture Overview](../../../docs/architecture.md) — System design and module composition
- [Backend Style Guide](../../../docs/backend-styleguide.md) — Coding conventions