{"id":17681298,"url":"https://github.com/madeindjs/nestjs-graphile-worker","last_synced_at":"2025-04-14T19:06:41.219Z","repository":{"id":39652221,"uuid":"406428545","full_name":"madeindjs/nestjs-graphile-worker","owner":"madeindjs","description":"A Nest.js wrapper for Graphile Worker","archived":false,"fork":false,"pushed_at":"2025-04-08T21:47:23.000Z","size":1126,"stargazers_count":46,"open_issues_count":2,"forks_count":18,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-14T19:06:21.592Z","etag":null,"topics":["graphile-worker","nestjs"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/nestjs-graphile-worker","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/madeindjs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-09-14T15:43:40.000Z","updated_at":"2025-04-14T12:19:45.000Z","dependencies_parsed_at":"2024-06-21T16:45:25.801Z","dependency_job_id":null,"html_url":"https://github.com/madeindjs/nestjs-graphile-worker","commit_stats":{"total_commits":48,"total_committers":7,"mean_commits":6.857142857142857,"dds":"0.16666666666666663","last_synced_commit":"9e91da39cda1aad65625344c777da36e5753dde1"},"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/madeindjs%2Fnestjs-graphile-worker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/madeindjs%2Fnestjs-graphile-worker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/madeindjs%2Fnestjs-graphile-worker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/madeindjs%2Fnestjs-graphile-worker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/madeindjs","download_url":"https://codeload.github.com/madeindjs/nestjs-graphile-worker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248943456,"owners_count":21186958,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphile-worker","nestjs"],"created_at":"2024-10-24T09:10:44.907Z","updated_at":"2025-04-14T19:06:41.189Z","avatar_url":"https://github.com/madeindjs.png","language":"TypeScript","readme":"# Graphile Worker for Nest.js\n\n[![npm version](https://badge.fury.io/js/nestjs-graphile-worker.svg)](https://badge.fury.io/js/nestjs-graphile-worker)\n![Test status](https://github.com/madeindjs/nestjs-graphile-worker/actions/workflows/main.yml/badge.svg)\n\nA [Nest.js](https://github.com/nestjs/nest) wrapper for [Graphile Worker](https://github.com/graphile/worker).\n\nWhat is Graphile worker ?\n\n\u003e Job queue for PostgreSQL running on Node.js - allows you to run jobs (e.g. sending emails, performing calculations, generating PDFs, etc) \"in the background\" so that your HTTP response/application code is not held up. Can be used with any PostgreSQL-backed application. Pairs beautifully with [PostGraphile](https://www.graphile.org/postgraphile/) or [PostgREST](http://postgrest.org/).\n\nWhy you should prefer Graphile Worker instead of [Bull](https://github.com/nestjs/bull) ?\n\n1. You already have a PostgreSQL in your stack (and you don't want to add a Redis server)\n\n## Features\n\n- provide a module `GraphileWorkerModule` to setup the runner using `asRoot` or `asRootAsync`\n- provide a `WorkerService` to add jobs or start runner\n- provide a `@OnWorkerEvent` decorator to add custom behavior on `job:success` for example\n- provide a `@Task(name)` decorator to define your injectable tasks\n\n## Installation\n\n```sh\nnpm install nestjs-graphile-worker\nyarn add nestjs-graphile-worker\npnpm add nestjs-graphile-worker\n```\n\n## Usage\n\n### 1. Setup the module\n\nIn order, to setup the library, you need to import and initialize [`GraphileWorkerModule`](./src/graphile-worker.module.ts).\n\nYou can do it using `forRoot` method:\n\n```ts\n// src/app.module.ts\nimport { GraphileWorkerModule } from \"nest-graphile-worker\";\nimport { Module } from \"@nestjs/common\";\nimport { AppController } from \"./app.controller\";\n\n@Module({\n  imports: [\n    GraphileWorkerModule.forRoot({\n      connectionString: \"postgres://example:password@postgres/example\",\n    }),\n  ],\n  controllers: [AppController],\n  providers: [],\n})\nexport class AppModule {}\n```\n\nOr using `forRootAsync`:\n\n```ts\n// src/app.module.ts\nimport { GraphileWorkerModule } from \"nestjs-graphile-worker\";\nimport { Module } from \"@nestjs/common\";\nimport { ConfigModule, ConfigService } from \"@nestjs/config\";\nimport { AppController } from \"./app.controller\";\nimport { helloTask } from \"./hello.task\";\n\n@Module({\n  imports: [\n    ConfigModule.forRoot(),\n    GraphileWorkerModule.forRootAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: (config: ConfigService) =\u003e ({\n        connectionString: config.get(\"PG_CONNECTION\"),\n        taskList: {\n          hello: helloTask,\n        },\n      }),\n    }),\n  ],\n  controllers: [AppController],\n  providers: [],\n})\nexport class AppModule {}\n```\n\nThe module configuration is [`GraphileWorkerConfiguration`](./src/interfaces/module-config.interfaces.ts), which is a wrapper around Graphile's [`RunnerOptions`](https://github.com/graphile/worker/blob/7feecdde5692569f006d3379f4caee01c4482707/src/interfaces.ts#L716)\n\n```ts\ntype GraphileWorkerConfiguration = Omit\u003cRunnerOptions, \"events\" | \"taskList\"\u003e;\n```\n\nThis means you can pass any configuration to the runner, like [Recurring tasks (crontab)](https://worker.graphile.org/docs/cron):\n\n```ts\n// src/app.module.ts\n@Module({\n  imports: [\n    GraphileWorkerModule.forRoot({\n      connectionString: \"postgres://example:password@postgres/example\",\n      crontab: [' * * * * * taskIdentifier ?priority=1 {\"foo\": \"bar\"}'].join(\n        \"\\n\",\n      ),\n    }),\n  ],\n  controllers: [AppController],\n  providers: [],\n})\nexport class AppModule {}\n```\n\n### 2. Create task\n\nTo create task you need to define an `@Injectable` class with `@Task(name)` decorator containing a decorated method with `@TaskHandler`:\n\n```ts\n// src/hello.task.ts\nimport { Injectable, Logger } from \"@nestjs/common\";\nimport type { Helpers } from \"graphile-worker\";\nimport { Task, TaskHandler } from \"../../src/index\";\n\n@Injectable()\n@Task(\"hello\")\nexport class HelloTask {\n  private logger = new Logger(HelloTask.name);\n\n  @TaskHandler()\n  handler(payload: any, _helpers: Helpers) {\n    this.logger.log(`handle ${JSON.stringify(payload)}`);\n  }\n}\n```\n\nThen do not forget to register this class as provider in your module:\n\n```ts\n// src/app.module.ts\nimport { Module } from \"@nestjs/common\";\nimport { HelloTask } from \"./hello.task\";\n// ...\n\n@Module({\n  imports: [\n    /* ... */\n  ],\n  controllers: [\n    /* ... */\n  ],\n  providers: [HelloTask],\n})\nexport class AppModule {}\n```\n\n### 3. Create jobs\n\nYou can use [`WorkerService`](./src/services/worker.service.ts) which is a wrapper of [`graphile-worker`](graphile-worker)'s [`Runner`](https://worker.graphile.org/docs/library/run#runner) instance. [`WorkerService`](./src/services/worker.service.ts) let you add job easily.\n\n```ts\nimport { WorkerService } from \"nestjs-graphile-worker\";\nimport { Controller, HttpCode, Post } from \"@nestjs/common\";\n\n@Controller()\nexport class AppController {\n  constructor(private readonly graphileWorker: WorkerService) {}\n\n  @Post()\n  @HttpCode(201)\n  async addJob() {\n    await this.graphileWorker.addJob(\"hello\", { hello: \"world\" });\n  }\n\n  @Post(\"bulk\")\n  @HttpCode(201)\n  async addJobs() {\n    const jobs = new Array(100)\n      .fill(undefined)\n      .map((_, i) =\u003e ({ identifier: \"hello\", payload: { hello: i } }));\n\n    return this.graphileWorker.addJobs(jobs);\n  }\n}\n```\n\n### 4. Start runner\n\nAdd [`WorkerService.run`](https://github.com/madeindjs/nestjs-graphile-worker/blob/7ed5a99dcd28a11259031e0e738b0cf5a4050904/src/services/worker.service.ts#L31-L42) in `main.ts` file:\n\n```ts\nimport { WorkerService } from \"nestjs-graphile-worker\";\nimport { NestFactory } from \"@nestjs/core\";\nimport { AppModule } from \"./app.module\";\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.get(WorkerService).run();\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n### 5. Listen any Graphile's event\n\nYou can use `@OnWorkerEvent` decorator to listen any [Graphile Worker event](https://worker.graphile.org/docs/worker-events). You simply have to:\n\n1. `@GraphileWorkerListener` decorator on your class\n2. set `@OnWorkerEvent(eventName)` on your method\n\n```ts\nimport { Injectable, Logger } from \"@nestjs/common\";\nimport { WorkerEventMap } from \"graphile-worker\";\nimport { GraphileWorkerListener, OnWorkerEvent } from \"../../src/index\";\n\n@Injectable()\n@GraphileWorkerListener()\nexport class AppService {\n  private readonly logger = new Logger(AppService.name);\n\n  @OnWorkerEvent(\"job:success\")\n  onJobSuccess({ job }: WorkerEventMap[\"job:success\"]) {\n    this.logger.debug(`job #${job.id} finished`);\n  }\n\n  @OnWorkerEvent(\"job:error\")\n  onJobError({ job, error }: WorkerEventMap[\"job:error\"]) {\n    this.logger.error(`job #${job.id} fail ${JSON.stringify(error)}`);\n  }\n}\n```\n\n## Sample\n\nYou can find a [sample](./sample/) using this library. To run it, simply `npm install` and then:\n\n```sh\ndocker-compose up\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmadeindjs%2Fnestjs-graphile-worker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmadeindjs%2Fnestjs-graphile-worker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmadeindjs%2Fnestjs-graphile-worker/lists"}