@arturwojnar/hermes-mongodb
Version:
Production-Ready TypeScript Outbox Pattern for MongoDB
50 lines (49 loc) • 2.06 kB
TypeScript
import { ClientSession, Db, MongoClient, ObjectId, type ChangeStreamInsertDocument, type ResumeToken } from 'mongodb';
import { type AsyncOrSync } from 'ts-essentials';
type OutboxMessageModel<Event> = {
_id: ObjectId;
occurredAt: Date;
data: Event;
partitionKey: string;
sentAt?: Date;
};
type OutboxConsumerModel = {
_id: ObjectId;
lastProcessedId: ObjectId | null;
resumeToken: ResumeToken;
partitionKey: string;
lastUpdatedAt: Date | null;
createdAt: Date;
};
type OutboxMessageStream<Event> = ChangeStreamInsertDocument<OutboxMessageModel<Event>>;
type Start = () => Promise<Stop>;
type Stop = () => Promise<void>;
type Publish<Event> = (event: Event | Event[], sessionOrCallback?: ClientSession | SaveWithEventCallback | undefined) => Promise<void>;
type SaveWithEventCallback = (session: ClientSession, db: Db, client: MongoClient) => Promise<void>;
type OutboxConsumer<Event extends OutboxEvent> = {
start: Start;
publish: Publish<Event>;
withScope: WithScope<Event>;
};
type ErrorCallback = (error: unknown) => void;
type NowFunction = () => Date;
type ConsumerCreationParams<Event> = {
client: MongoClient;
db: Db;
publish: (event: Event) => AsyncOrSync<void> | never;
partitionKey?: string;
waitAfterFailedPublishMs?: number;
shouldDisposeOnSigterm?: boolean;
saveTimestamps?: boolean;
onFailedPublish?: ErrorCallback;
onDbError?: ErrorCallback;
now?: NowFunction;
};
type OutboxScope<Event extends OutboxEvent> = {
session: ClientSession;
client: MongoClient;
publish: (event: Event | Event[]) => Promise<void>;
};
type OutboxEvent = object;
type WithScope<Event extends OutboxEvent> = (scopeFn: (scope: OutboxScope<Event>) => Promise<void>) => Promise<void>;
export { type ConsumerCreationParams, type ErrorCallback, type OutboxConsumer, type OutboxConsumerModel, type OutboxEvent, type OutboxMessageModel, type OutboxMessageStream, type OutboxScope, type Publish, type SaveWithEventCallback, type Start, type Stop, type WithScope, };