DRY Castore EventType
definition using JSON Schemas and json-schema-to-ts
# npm
npm install @castore/json-schema-event
# yarn
yarn add @castore/json-schema-event
This package has @castore/core
and json-schema-to-ts
(above v2) as peer dependencies, so you will have to install them as well:
# npm
npm install @castore/core json-schema-to-ts
# yarn
yarn add @castore/core json-schema-to-ts
import { JSONSchemaEventType } from '@castore/json-schema-event';
const userCreatedPayloadSchema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'string' },
},
required: ['name', 'age'],
additionalProperties: false,
} as const; // 👈 Don't forget the "as const" statement
// (Cf json-schema-to-ts documentation)
const userCreatedMetadataSchema = {
type: 'object',
properties: {
invitedBy: { type: 'string' },
},
additionalProperties: false,
} as const;
// 👇 generics are correctly inferred
const userCreatedEventType = new JSONSchemaEventType({
type: 'USER_CREATED',
payloadSchema: userCreatedPayloadSchema,
metadataSchema: userCreatedMetadataSchema,
});
👇 Equivalent to:
import { EventType } from '@castore/core';
const userCreatedEventType = new EventType<
'USER_CREATED',
{ name: string; age: number },
{ invitedBy?: string }
>({ type: 'USER_CREATED' });
JSONSchemaEventType
implements the EventType
class and adds the following properties to it:
payloadSchema (?object)
: The event type payload JSON schema
const payloadSchema = userCreatedEventType.payloadSchema;
// => userCreatedPayloadSchema
metadataSchema (?object)
: The event type metadata JSON schema
const metadataSchema = userCreatedEventType.metadataSchema;
// => userCreatedMetadataSchema