{"_id":"@asanovr/nestjs-hasura","name":"@asanovr/nestjs-hasura","dist-tags":{"latest":"4.0.0"},"versions":{"4.0.0":{"name":"@asanovr/nestjs-hasura","version":"4.0.0","description":"Badass utilities for integrating Hasura and NestJS","author":{"name":"Jesse Carter","email":"jesse.r.carter@gmail.com"},"homepage":"https://github.com/golevelup/nestjs#readme","license":"MIT","keywords":["NestJS","hasura","graphql","gql"],"main":"lib/index.js","typings":"lib/index.d.ts","directories":{"lib":"lib","test":"__tests__"},"repository":{"type":"git","url":"git+https://github.com/asanovr/nestjs.git"},"scripts":{"build":"tsc --build tsconfig.build.json","build:watch":"tsc --build tsconfig.build.json --watch","test":"jest"},"bugs":{"url":"https://github.com/golevelup/nestjs/issues"},"publishConfig":{"access":"public"},"dependencies":{"@golevelup/nestjs-common":"^2.0.1","@golevelup/nestjs-discovery":"^4.0.1","@golevelup/nestjs-modules":"^0.7.1","@hasura/metadata":"^1.0.2","js-yaml":"^4.1.0","zod":"^3.3.4"},"jest":{"moduleFileExtensions":["js","json","ts"],"rootDir":"src","testRegex":".spec.ts$","transform":{"^.+\\.ts$":"ts-jest"},"coverageDirectory":"../coverage","testEnvironment":"node"},"gitHead":"83abc8861cf5f8df94b8cd39964f41ce728aff6d","devDependencies":{"@types/js-yaml":"^3.12.5","ts-toolbelt":"^9.6.0"},"_id":"@asanovr/nestjs-hasura@4.0.0","_nodeVersion":"16.15.1","_npmVersion":"lerna/3.22.1/node@v16.15.1+arm64 (darwin)","dist":{"integrity":"sha512-hbHm6iNvhdVHIQRZ8CljhUuhEnWxyvlIqhWEwbUXb81/qXOSGUyCYgwNEKeI3Jf4r9sjVbuRfMBppUZA9U+I0g==","shasum":"6f40d26f65742f34f7a9999eb016398df1fc3f7e","tarball":"https://registry.npmjs.org/@asanovr/nestjs-hasura/-/nestjs-hasura-4.0.0.tgz","fileCount":56,"unpackedSize":189439,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCK1tEKgx3QUrjk4Po3q9QEudaaRlcdAcFSoVeUY1RhTwIgdhZWBMIExMNwvlucAqtnbIi44y4cofyO208qcb8YunU="}]},"_npmUser":{"name":"asanovr","email":"bioforge91@gmail.com"},"maintainers":[{"name":"asanovr","email":"bioforge91@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/nestjs-hasura_4.0.0_1693545916705_0.7397612494068773"},"_hasShrinkwrap":false}},"time":{"created":"2023-09-01T05:25:16.597Z","4.0.0":"2023-09-01T05:25:16.953Z","modified":"2023-09-01T05:25:17.335Z"},"maintainers":[{"name":"asanovr","email":"bioforge91@gmail.com"}],"description":"Badass utilities for integrating Hasura and NestJS","homepage":"https://github.com/golevelup/nestjs#readme","keywords":["NestJS","hasura","graphql","gql"],"repository":{"type":"git","url":"git+https://github.com/asanovr/nestjs.git"},"author":{"name":"Jesse Carter","email":"jesse.r.carter@gmail.com"},"bugs":{"url":"https://github.com/golevelup/nestjs/issues"},"license":"MIT","readme":"# @golevelup/nestjs-hasura\n\nLeverage NestJS to make incorporating business logic and event processing easier with Hasura. 🚀\n\n<p align=\"center\">\n<a href=\"https://www.npmjs.com/package/@golevelup/nestjs-hasura\"><img src=\"https://img.shields.io/npm/v/@golevelup/nestjs-hasura.svg?style=flat\" alt=\"version\" /></a>\n<a href=\"https://www.npmjs.com/package/@golevelup/nestjs-hasura\"><img alt=\"downloads\" src=\"https://img.shields.io/npm/dt/@golevelup/nestjs-hasura.svg?style=flat\"></a>\n<img alt=\"license\" src=\"https://img.shields.io/npm/l/@golevelup/nestjs-hasura.svg\">\n</p>\n\n- [@golevelup/nestjs-hasura](#golevelupnestjs-hasura)\n  - [Features](#features)\n  - [Usage](#usage)\n    - [Install](#install)\n    - [Import](#import)\n    - [Configuration](#configuration)\n    - [Usage](#usage-1)\n      - [Integrating with your NestJS app](#integrating-with-your-nestjs-app)\n      - [Automatically Synchronize Hasura Metadata](#automatically-synchronize-hasura-metadata)\n      - [Opting Out](#opting-out)\n      - [Registering Table Event Handlers](#registering-table-event-handlers)\n      - [Registering Scheduled Event Handlers](#registering-scheduled-event-handlers)\n      - [Retry Configuration](#retry-configuration)\n      - [Configuring Hasura Environment Variables](#configuring-hasura-environment-variables)\n      - [Usage with Interceptors, Guards and Filters](#usage-with-interceptors-guards-and-filters)\n    - [Related Hasura Documentation](#related-hasura-documentation)\n      - [Concepts](#concepts)\n      - [Tutorials](#tutorials)\n  - [Contribute](#contribute)\n  - [License](#license)\n\n## Features\n\n- 🎉 Exposes an API endpoint from your NestJS application at to be used for event processing from Hasura. Defaults to `/hasura/events/` but can be easily configured\n\n- 🔒 Automatically validates that the event payload was actually sent from Hasura using configurable secrets\n\n- 🕵️ Discovers methods from your application and automatically turns them into Hasura event handlers. Supports insert, update and delete events from your tables as well as scheduled events based on a CRON schedule\n\n- 🧭 Routes incoming webhook payloads to the correct event handler based on configuration so you can maintain a single webhook endpoint for Hasura\n\n- 🔌 Optionally supports automatic management of your Hasura metadata files which means that your application code can be the source of truth for configuration of events. This reduces a ton of boilerplate and developer overhead\n\n## Usage\n\n### Install\n\n`npm install ---save @golevelup/nestjs-hasura`\n\nor\n\n`yarn add @golevelup/nestjs-hasura`\n\n### Import\n\nImport and add `HasuraModule` to the `imports` section of the consuming module (most likely `AppModule`). In order to ensure that your Hasura events webhook endpoint is secure, the module requires configuration for an HTTP header name and value that will be used to verify that the event actually came from Hasura.\n\n### Configuration\n\nThe Hasura Module supports both the `forRoot` and `forRootAsync` patterns for configuration, so you can easily retrieve the necessary config values from a `ConfigService` or other provider.\n\n### Usage\n\n#### Integrating with your NestJS app\n\nThe `HasuraModule` makes it easy to reuse the same events API endpoint for all events that you create in Hasura. The internal routing mechanism on the NestJS side ensures that the all events coming in through the endpoint will be sent to the correct handler. The endpoint provided defaults to `/hasura/events`. This can be overriden with the module by specifying an alternative `controllerPrefix` so for example you could set this to `webhooks` and the resulting endpoint would be available at `/webhooks/events`.\n\n#### Automatically Synchronize Hasura Metadata\n\nOne of the more powerful features of this Module is the ability to automatically generate the necessary Hasura metadata for your event handlers instead of having to worry about configuring each handler individually. Under the hood, this uses the [`@hasura/metadata`](https://www.npmjs.com/package/@hasura/metadata) to generate and merge changes to your `tables.yaml` and `cron_triggers.yaml` files.\n\nIf you decide to opt into this functionality, you should include the optional `managedMetaDataConfig` object when importing the HasuraModule into your application.\n\n```typescript\nimport { HasuraModule } from '@golevelup/nestjs-hasura';\n\n@Module({\n  imports: [\n    HasuraModule.forRoot(HasuraModule, {\n      webhookConfig: {\n        secretFactory: secret,\n        secretHeader: secretHeader,\n      },\n      managedMetaDataConfig: {\n        dirPath: join(process.cwd(), 'hasura/metadata'),\n        secretHeaderEnvName: 'HASURA_NESTJS_WEBHOOK_SECRET_HEADER_VALUE',\n        nestEndpointEnvName: 'NESTJS_EVENT_WEBHOOK_ENDPOINT',\n        defaultEventRetryConfig: {\n          intervalInSeconds: 15,\n          numRetries: 3,\n          timeoutInSeconds: 100,\n          toleranceSeconds: 21600,\n        },\n      },\n    }),\n  ],\n})\nexport class AppModule {\n  // ...\n}\n```\n\nIt is recommended that you conditionally add this configuration based on the Node Environment as this should only be used in development environments to track the necessary changes to your metadata yaml files so that they can be tracked in source control.\n\nAfter generating changes to these files you should make sure they are applied against your Hasura instance using the CLI command:\n\n```\nhasura metadata apply\n```\n\n#### Opting Out\n\nIf you decide to opt out of automatic metadata synchronization it is up to you to ensure that the secret header name and values match. When creating the event in the Hasura console, you should set these values such that they match the configuration provided to the `HasuraModule` configuration in your NestJS application. This ensures that only Hasura can trigger events in your system.\n\n#### Registering Table Event Handlers\n\nDecorate methods in your NestJS providers in order to have them be automatically attached as event handlers for incoming Hasura events. The event payload will be analyzed and routed to your provider methods based on the configuration provided in the decorator.\n\n```typescript\nimport {\n  TrackedHasuraEventHandler,\n  HasuraUpdateEvent,\n  HasuraInsertEvent,\n} from '@golevelup/nestjs-hasura';\n\n@Injectable()\nclass UsersService {\n  @TrackedHasuraEventHandler({\n    triggerName: 'user-created',\n    tableName: 'user',\n    definition: { type: 'insert' },\n  })\n  handleUserCreated(evt: HasuraInsertEvent<User>) {}\n\n  @TrackedHasuraEventHandler({\n    triggerName: 'user-updated',\n    tableName: 'user',\n    definition: { type: 'update', columns: ['avatarUrl'] },\n  })\n  handleUserUpdated(evt: HasuraUpdateEvent<User>) {}\n}\n```\n\n#### Registering Scheduled Event Handlers\n\n```typescript\nimport { TrackedHasuraScheduledEventHandler } from '@golevelup/nestjs-hasura';\n\n@Injectable()\nclass RecurringJobService {\n  @TrackedHasuraScheduledEventHandler({\n    cronSchedule: CommonCronSchedules.EveryMinute,\n    name: 'every-minute',\n    payload: {},\n    comment: 'this is my comment',\n  })\n  public async cronTask(evt: any) {\n    this.logger.log(evt);\n  }\n}\n```\n\n#### Retry Configuration\n\nRetry configuration for both Table Event handlers as well as Scheduled Event handlers can be configured on the individual decorator or you can provide a default retry configuration at the module level that will be used for any event handler that does not explicitly provide its own retry settings.\n\n#### Configuring Hasura Environment Variables\n\nYou should provide ENV variables to your Hasura instance that map the webhook endpoint and secret header values for communication to your NestJS application.\n\nIn the examples above, `HASURA_NESTJS_WEBHOOK_SECRET_HEADER_VALUE` and `NESTJS_EVENT_WEBHOOK_ENDPOINT` were used. The webhook endpoint should point to the automatically scaffolded events endpoint eg:\n`https://my-nest-app.com/api/hasura/events`\n\n#### Usage with Interceptors, Guards and Filters\n\nThis library is built using an underlying NestJS concept called `External Contexts` which allows for methods to be included in the NestJS lifecycle. This means that Guards, Interceptors and Filters (collectively known as \"enhancers\") can be used in conjunction with Hasura event handlers. However, this can have unwanted/unintended consequences if you are using _Global_ enhancers in your application as these will also apply to all Hasura event handlers. If you were previously expecting all contexts to be regular HTTP contexts, you may need to add conditional logic to prevent your enhancers from applying to Hasura event handlers.\n\nYou can identify Hasura event contexts by their context type, `'hasura_event'`:\n\n```typescript\n@Injectable()\nclass ExampleInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler<any>) {\n    const contextType = context.getType<'http' | 'hasura_event'>();\n\n    // Do nothing if this is a Hasura event\n    if (contextType === 'hasura_event') {\n      return next.handle();\n    }\n\n    // Execute custom interceptor logic for HTTP request/response\n    return next.handle();\n  }\n}\n```\n\n### Related Hasura Documentation\n\n#### Concepts\n\nhttps://hasura.io/docs/1.0/graphql/manual/event-triggers/index.html#event-triggers\n\n#### Tutorials\n\nhttps://hasura.io/docs/1.0/graphql/manual/getting-started/first-event-trigger.html\nhttps://hasura.io/event-triggers\n\n## Contribute\n\nContributions welcome! Read the [contribution guidelines](../../CONTRIBUTING.md) first.\n\n## License\n\n[MIT License](../../LICENSE)\n","readmeFilename":"README.md"}