Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: validate event input #175

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
}
42 changes: 29 additions & 13 deletions packages/core/src/event/eventType.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
import type { EventDetail } from './eventDetail';
import { reservedEventTypes } from './reservedEventTypes';

export type ParsedCandidate<T> =
| {
isValid: false;
parsedCandidate?: never;
parsingErrors: [Error, ...Error[]];
}
| {
isValid: true;
parsedCandidate: T;
parsingErrors?: never;
};

export type CandidateParser<T> = (candidate: EventDetail) => ParsedCandidate<T>;

export type EventDetailParser<
TYPE extends string = string,
PAYLOAD = unknown,
METADATA = unknown,
> = CandidateParser<EventDetail<TYPE, PAYLOAD, METADATA>>;

export class EventType<
TYPE extends string = string,
PAYLOAD = string extends TYPE ? unknown : never,
Expand All @@ -10,26 +30,22 @@ export class EventType<
detail: EventDetail<TYPE, PAYLOAD, METADATA>;
};
type: TYPE;
parseEventDetail?: (candidate: unknown) =>
| {
isValid: true;
parsedEventDetail: EventDetail<TYPE, PAYLOAD, METADATA>;
parsingErrors?: never;
}
| {
isValid: false;
parsedEventDetail?: never;
parsingErrors?: [Error, ...Error[]];
};
parseEventDetail?: EventDetailParser<TYPE, PAYLOAD, METADATA> | undefined;

constructor({ type }: { type: TYPE }) {
constructor({
type,
parseEventDetail,
}: {
type: TYPE;
parseEventDetail?: EventDetailParser<TYPE, PAYLOAD, METADATA> | undefined;
}) {
if (reservedEventTypes.has(type)) {
throw new Error(
`${type} is a reserved event type. Please chose another one.`,
);
}

this.type = type;
this.parseEventDetail = parseEventDetail;
}
}

Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/event/eventType.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ const eventType = new EventType({ type: 'some type' });

describe('event store', () => {
it('has correct properties', () => {
expect(new Set(Object.keys(eventType))).toStrictEqual(new Set(['type']));
expect(new Set(Object.keys(eventType))).toStrictEqual(
new Set(['type', 'parseEventDetail']),
);
});

it('raises an error if type is reserved', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export class EventDetailParserNotDefinedError extends Error {
constructor(type: string) {
super(
`Can not validate input because EventType "${type}" has no parseEventDetail method defined.`,
);
}
}
15 changes: 15 additions & 0 deletions packages/core/src/eventStore/errors/eventDetailTypeDoesNotExist.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export class EventDetailTypeDoesNotExistError extends Error {
constructor({
type,
allowedTypes,
}: {
type: string;
allowedTypes: string[];
}) {
super(
`${type} is not a valid event detail type. Allowed types are ${allowedTypes.join(
', ',
)}.`,
);
}
}
2 changes: 2 additions & 0 deletions packages/core/src/eventStore/errors/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export * from './aggregateNotFound';
export * from './eventAlreadyExists';
export * from './eventDetailTypeDoesNotExist';
export * from './eventDetailParserNotDefined';
export * from './undefinedEventStorageAdapter';
56 changes: 55 additions & 1 deletion packages/core/src/eventStore/eventStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import { GroupedEvent } from '~/event/groupedEvent';
import type { EventStorageAdapter } from '~/eventStorageAdapter';
import type { $Contravariant } from '~/utils';

import { EventDetailParser } from '../event/eventType';
import {
EventDetailParserNotDefinedError,
EventDetailTypeDoesNotExistError,
} from './errors';
import { AggregateNotFoundError } from './errors/aggregateNotFound';
import { UndefinedEventStorageAdapterError } from './errors/undefinedEventStorageAdapter';
import type {
Expand All @@ -20,6 +25,7 @@ import type {
AggregateGetter,
AggregateSimulator,
Reducer,
ValidateEventDetail,
} from './types';

export class EventStore<
Expand Down Expand Up @@ -178,10 +184,58 @@ export class EventStore<
*/
) as Promise<{ events: EVENT_DETAILS[] }>;

const shouldValidateEventDetail = (
validate: ValidateEventDetail,
eventDetailType: string,
eventType?: EventType,
): eventType is EventType => {
if (validate === false) {
return false;
}

if (eventType === undefined) {
throw new EventDetailTypeDoesNotExistError({
type: eventDetailType,
allowedTypes: this.eventTypes.map(({ type }) => type),
});
}

if (validate === 'auto' && eventType.parseEventDetail === undefined) {
return false;
}

return true;
};

const validateEventDetail = (
eventDetail: EventDetail,
eventDetailParser?: EventDetailParser,
) => {
if (eventDetailParser === undefined) {
throw new EventDetailParserNotDefinedError(eventDetail.type);
}

const { parsingErrors, isValid } = eventDetailParser(eventDetail);

if (isValid) {
return;
}

throw new Error(parsingErrors[0].message);
};

this.pushEvent = async (
eventDetail,
{ prevAggregate, force = false } = {},
{ prevAggregate, force = false, validate = 'auto' } = {},
) => {
const eventType = this.eventTypes.find(
({ type }) => type === eventDetail.type,
);

if (shouldValidateEventDetail(validate, eventDetail.type, eventType)) {
validateEventDetail(eventDetail, eventType.parseEventDetail);
}

const eventStorageAdapter = this.getEventStorageAdapter();

const { event } = (await eventStorageAdapter.pushEvent(eventDetail, {
Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/eventStore/eventStore.type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
EventStoreAggregate,
EventStoreEventDetails,
GetAggregateOptions,
ValidateEventDetail,
} from '~/eventStore';

import {
Expand Down Expand Up @@ -109,7 +110,12 @@ assertPushEventInput1;

const assertPushEventInput2: A.Equals<
Parameters<typeof pokemonsEventStore.pushEvent>[1],
{ prevAggregate?: PokemonAggregate | undefined; force?: boolean } | undefined
| {
prevAggregate?: PokemonAggregate | undefined;
force?: boolean;
validate?: ValidateEventDetail;
}
| undefined
> = 1;
assertPushEventInput2;

Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/eventStore/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export type EventsGetter<EVENT_DETAIL extends EventDetail> = (
options?: EventsQueryOptions,
) => Promise<{ events: EVENT_DETAIL[] }>;

export type ValidateEventDetail = boolean | 'auto';

export type EventPusher<
EVENT_DETAILS extends EventDetail,
$EVENT_DETAILS extends EventDetail,
Expand All @@ -37,7 +39,11 @@ export type EventPusher<
event: $EVENT_DETAILS extends EventDetail
? OptionalTimestamp<$EVENT_DETAILS>
: $EVENT_DETAILS,
options?: { prevAggregate?: $AGGREGATE; force?: boolean },
options?: {
prevAggregate?: $AGGREGATE;
force?: boolean;
validate?: ValidateEventDetail;
},
) => Promise<{ event: EVENT_DETAILS; nextAggregate?: AGGREGATE }>;

export type AggregateIdsLister = (
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export type { Aggregate } from './aggregate';
export { EventType } from './event/eventType';
export { EventType, EventDetailParser } from './event/eventType';
export type { EventTypeDetail, EventTypeDetails } from './event/eventType';
export { GroupedEvent } from './event/groupedEvent';
export { __REPLAYED__, __AGGREGATE_EXISTS__ } from './event/reservedEventTypes';
Expand Down
Loading
Loading