Skip to main content

How do I add a new event?

Objective: This article explains how to add a new event in a module.

Prerequisites:

  • You have an implementation for a factory for your desired database model. (if applicable).
    • See modules/<module>/core/factories.ts

Steps:

  1. Add a new event schema to the module.
    • modules/<module>/core/events/schemas/
  2. Export it in the index file.
    • modules/<module>/core/events/schemas/index.ts
  3. Add a new event.
    • modules/<module>/core/events/
  4. Export it in the index file.
    • modules/<module>/core/events/index.ts
  5. Run pnpm run schemas to generate the event schema.

Example:

// modules/<module>/core/events/schemas/my-models.ts

import { BaseEventPayload } from '@hectare/platform.components.common'
import { Context, ContextFactory } from '@hectare/platform.components.context'
import { MyModel } from '../../models/index.js'
import { MyModelsFactory } from '../../factories.js'

export class MyModelCreated extends BaseEventPayload {
model: MyModel

constructor(context: Context, model: MyModel) {
super(context.event.correlationId, context.user.id, context.user.organisationId)
this.model = model
}

public static schema(): string {
return JSON.stringify(new MarketUpdateCreated(ContextFactory.build(), MyModelsFactory.build()))
}
}
// modules/<module>/core/events/my-models.ts

import { BaseEvent } from '@hectare/platform.components.common'
import { Context } from '@hectare/platform.components.context'
import { MyModel } from '../models/index.js'
import { MyModelCreated } from './schemas/my-models.js'

export class MyModelCreatedEvent extends BaseEvent<MyModelCreated> {
constructor(context: Context, model: MyModel) {
super('MyModelCreated', context.event.module)
this.payload = new MyModelCreated(context, model)
}
}

Usage:

// Publish one event:

const event = new MyModelCreatedEvent(context, model)

context.events.publishAfterCommit(event)
// Publish many events:

const events = [
new MyModelCreatedEvent(context, modelA),
new MyModelCreatedEvent(context, modelB),
...
]

context.events.publishBatchAfterCommit(events)

Related Articles: