import { Injectable } from "@nestjs/common"; import { WorkWithMetadataHandler, PgBoss, SendOptions, ScheduleOptions, WorkOptions, } from "pg-boss"; import { Inject } from "@nestjs/common"; import { PGBOSS_TOKEN } from "./utils/consts"; import { transformOptions } from "./utils/helpers"; @Injectable() export class PgBossService { private pgBoss: PgBoss; constructor(@Inject(PGBOSS_TOKEN) boss: PgBoss) { this.pgBoss = boss; } get boss(): PgBoss { return this.pgBoss; } async scheduleJob( name: string, data: TData, options?: SendOptions, ) { await this.pgBoss.createQueue(name); await this.pgBoss.send(name, data, options); } async scheduleCronJob( name: string, cron: string, data?: TData, options?: ScheduleOptions, ) { await this.pgBoss.createQueue(name); await this.pgBoss.schedule(name, cron, data ?? {}, options ?? {}); } async registerCronJob( name: string, cron: string, handler: WorkWithMetadataHandler, data?: TData, options?: ScheduleOptions, ) { await this.pgBoss.createQueue(name); await this.pgBoss.schedule(name, cron, data ?? {}, options ?? {}); await this.pgBoss.work( name, { ...transformOptions(options), includeMetadata: true } as WorkOptions & { includeMetadata: true; }, handler, ); } async registerJob( name: string, handler: WorkWithMetadataHandler, options?: WorkOptions, ) { await this.pgBoss.createQueue(name); await this.pgBoss.work( name, { ...options, includeMetadata: true }, handler, ); } }