@loctax/nest-pg-boss
v5.3.0
Published
Use pg-boss in your NestJS app
Downloads
6,962
Readme
@loctax/nest-pg-boss
Installation
npm install @loctax/nest-pg-bossUsage
Setup
To begin using @loctax/nest-pg-boss, initialize the root module:
import { PGBossModule } from "@loctax/nest-pg-boss";
// app.module.ts
@Module({
imports: [
PGBossModule.forRootAsync({
useFactory: (config: ConfigService) => ({
application_name: "default",
// Connection details
host: config.get<string>("DB_HOST"),
user: config.get<string>("DB_USERNAME"),
password: config.get<string>("DB_PASSWORD"),
database: config.get<string>("DB_DATABASE"),
schema: "public",
max: config.get<number>("DB_POOL_MAX"),
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}For a list of available settings, check out the pg-boss docs.
Jobs
// jobs.ts
import { createJob } from "@loctax/nest-pg-boss";
interface IFoobarJobData {
foo: string;
bar: boolean;
}
const FoobarJob = createJob<IFoobarJobData>("foobar");Create new Jobs
// module.ts
import { PGBossModule } from "@loctax/nest-pg-boss";
import { FoobarService } from "./service.ts";
@Module({
imports: PGBossModule.forJobs([FoobarJob]),
providers: [FoobarService],
})
class FoobarModule {}// service.ts
import { JobService } from "@loctax/nest-pg-boss";
import { FoobarJob, IFoobarJobData } from "./jobs.ts";
@Injectable()
class FoobarService {
constructor(
@FoobarJob.Inject()
private readonly foobarJobService: JobService<IFoobarJobData>
) {}
async sendJob() {
await this.foobarJobService.send({ foo: "oof", bar: true }, {});
}
}Process Jobs
Jobs can be processed by using the @FoobarJob.Handle() decorator.
// service.ts
@Injectable()
class FoobarService {
/* ... */
@FoobarJob.Handle()
async handleJob(job: Job<FoobarJobData>) {
// do something
}
}You can optionally pass an object with WorkOptions to .Handle():
@FoobarJob.Handle({ teamSize: 10, teamConcurrency: 2 })Inspect registered handlers
HandlerScannerService is exported from the global module. It returns every
@Job.Handle() method found in the Nest container together with its job name
and WorkOptions, which is useful for reporting per-queue capacity (e.g. a
teamSize gauge next to the queue backlog):
@Injectable()
class QueueMetricsService implements OnApplicationBootstrap {
constructor(private readonly handlerScanner: HandlerScannerService) {}
onApplicationBootstrap() {
for (const { metadata } of this.handlerScanner.getJobHandlers()) {
console.log(metadata.jobName, metadata.workOptions.teamSize ?? 1);
}
}
}Call it from onApplicationBootstrap or later so every provider has been
instantiated; the scan only sees providers that already have an instance.
Test
# everything
$ pnpm test
# unit tests only, no Docker required
$ pnpm test:unit
# e2e tests only, starts a Postgres testcontainer and needs Docker
$ pnpm test:e2eLicense
@loctax/nest-pg-boss is MIT licensed.
