nestjs icon indicating copy to clipboard operation
nestjs copied to clipboard

feat(hasura): implements a service to create and delete one off scheduled events

Open ivorpad opened this issue 3 years ago • 0 comments

Breaking changes

  • Replaces dirPath config from metadata directory with the root config directory: instead of dirPath: join(process.cwd(), 'hasura/metadata'), should be dirPath: join(process.cwd(), 'hasura')

New Features

  • This PR introduces the possibility to create One Off Scheduled Events via an Injectable Service. New configuration:
import { HasuraModule } from https://github.com/golevelup/nestjs;

@Module({
  imports: [
    HasuraModule.forRoot(HasuraModule, {
      webhookConfig: {
        secretFactory: secret,
        secretHeader: secretHeader,
        scheduledEventsHeader: 'nestjs-event-name',
        rootEndpoint: 'http://localhost:8080' /* optional: it will fallback to the root URL from Hasura config */
      },
      managedMetaDataConfig: {
        dirPath: join(process.cwd(), 'hasura') /* required: we now need to pass the root config directory */,
        secretHeaderEnvName: 'HASURA_NESTJS_WEBHOOK_SECRET_HEADER_VALUE',
        nestEndpointEnvName: 'NESTJS_EVENT_WEBHOOK_ENDPOINT',
        defaultEventRetryConfig: {
          intervalInSeconds: 15,
          numRetries: 3,
          timeoutInSeconds: 100,
          toleranceSeconds: 21600,
        },
      },
    }),
  ],
})
export class AppModule {
  // ...
}

To use this service inject it in the constructor of one of your services:

constructor(private readonly hasuraService: HasuraService) {}

and then schedule a new event:

const scheduledTime = add(
  new Date(
    new Date().toLocaleString("en-US", {
      timeZone: "Europe/Madrid",
    })
  ),
  { weeks: 1 }
);
const event = await this.hasuraService.createScheduledEvent({
  name: "send-email-one-week",
  comment: "",
  scheduled_time: scheduledTime,
  payload: {},
});

There's also a convenient webhook_url parameter that you can use to pass an arbitrary webhook to handle it outside of the NestJS app, but it has a trade off, you need to pass the webhook secret in payload and validate manually, but thought it was a nice to have.


Finally, to receive the event just decorate your handler with:

@TrackedHasuraScheduledEventHandler({ name: "send-email-one-week" })
emailUser() {
   console.log("emailUser");
}

I also added a method to delete one off events:

// import { ScheduledEventMode } from "@golevelup/nestjs-hasura"
await this.hasuraService.deleteScheduledEvent("event_id", ScheduledEventMode.ONE_OFF)

WIP:

  • Tests

ivorpad avatar May 26 '22 23:05 ivorpad