Skip to content

Effect integration

If your project uses Effect, the SDK ships an Effect-flavoured surface for the write path: creating events, dispatch jobs and audit logs through a unit of work. Its point is compile-time guarantees. A use case that does not go through UnitOfWork.commit does not compile; it does not merely throw at runtime.

The default neverthrow surface is unchanged and is what the rest of the SDK uses. Effect is an optional peer dependency (effect ^4.0.0-beta.70); Effect 4 is still in beta, so pin a beta version yourself until it ships stable.

Terminal window
npm install github:flowcatalyst/typescript-sdk#v0.29.0 effect@^4.0.0-beta.70
Use Surface
Writing events, dispatch jobs and audit logs; use cases with strict invariants @flowcatalyst/sdk/effect/usecase
HTTP CRUD (event types, principals, and so on), sync, scheduled-job runner The root SDK. It stays on neverthrow: re-wrapping reads adds noise and no invariant.

Entry points: @flowcatalyst/sdk/effect re-exports usecase; @flowcatalyst/sdk/effect/usecase is the typed surface. Both appear in the package exports map.

UnitOfWork.commit is the only function that produces a Sealed<E>. A use case returns Effect<Sealed<TEvent>, UseCaseError, UnitOfWork | ExecutionContext>, so at the type level it must use the unit of work. The brand is a module-private unique symbol, not exported, so outside code cannot forge one.

// Type error: OrderShipped is not assignable to Sealed<OrderShipped>
execute = (cmd) => Effect.succeed(rawEvent);
// Compiles: the only path to Sealed<E>
execute = (cmd) =>
Effect.gen(function* () {
const uow = yield* UnitOfWork;
return yield* uow.commit(event, cmd);
});

The neverthrow surface catches the same mistake at runtime with a token inside Result.success. Effect catches it when you save the file.

import { Effect } from 'effect';
import {
BaseDomainEvent,
DomainEvent,
ExecutionContext,
UnitOfWork,
ValidationError,
type UseCase,
} from '@flowcatalyst/sdk/effect/usecase';
import type { ExecutionContext as EventContext } from '@flowcatalyst/sdk/usecase';
interface OrderShippedData {
readonly orderId: string;
readonly carrierId: string;
readonly trackingNumber: string;
}
class OrderShipped extends BaseDomainEvent<OrderShippedData> {
constructor(ctx: EventContext, data: OrderShippedData) {
super(
{
eventType: 'orders:fulfillment:order:shipped',
specVersion: '1.0',
source: 'orders:fulfillment',
subject: DomainEvent.subject('fulfillment', 'order', data.orderId),
messageGroup: DomainEvent.messageGroup('fulfillment', 'order', data.orderId),
},
ctx,
data,
);
}
}
interface ShipOrderCommand {
readonly orderId: string;
readonly carrierId: string;
readonly trackingNumber: string;
}
class ShipOrderUseCase implements UseCase<ShipOrderCommand, OrderShipped> {
execute = (command: ShipOrderCommand) =>
Effect.gen(function* () {
const ctx = yield* ExecutionContext;
const uow = yield* UnitOfWork;
if (!command.trackingNumber) {
return yield* Effect.fail(
new ValidationError({ code: 'MISSING_TRACKING', message: 'trackingNumber is required' }),
);
}
return yield* uow.commit(new OrderShipped(ctx, command), command);
});
}

UnitOfWork has three operations: commit(event, command, persist?), commitDelete(aggregate, event, command, persist?) and emitEvent(event, command). persist runs your entity writes before the event is written.

Build the UnitOfWork layer from an OutboxManager (or from a raw driver with OutboxUnitOfWork.layerFromDriver(driver, clientId, options)), then provide the layer and an ExecutionContext at the boundary:

import { Effect } from 'effect';
import { OutboxManager, PgOutboxDriver } from '@flowcatalyst/sdk';
import { ExecutionContext, OutboxUnitOfWork, httpStatus } from '@flowcatalyst/sdk/effect/usecase';
const outboxManager = new OutboxManager(new PgOutboxDriver(pool), clientId);
const UoWLive = OutboxUnitOfWork.layer(outboxManager, { auditEnabled: true });
async function shipOrderRoute(command: ShipOrderCommand, principalId: string) {
const ctx = {
executionId: crypto.randomUUID(),
correlationId: crypto.randomUUID(),
causationId: null,
principalId,
initiatedAt: new Date(),
};
const program = new ShipOrderUseCase().execute(command).pipe(
Effect.map((sealed) => ({ ok: true as const, eventType: sealed.event.eventType })),
Effect.catchTags({
ValidationError: (e) => Effect.succeed({ ok: false as const, status: httpStatus(e), error: e }),
ConcurrencyError: (e) => Effect.succeed({ ok: false as const, status: httpStatus(e), error: e }),
InfrastructureError: (e) => Effect.succeed({ ok: false as const, status: httpStatus(e), error: e }),
}),
Effect.provide(UoWLive),
Effect.provideService(ExecutionContext, ctx),
);
return Effect.runPromise(program);
}

If you forget Effect.provide(UoWLive) or the ExecutionContext, Effect.runPromise is a compile error, because the requirements type R is not never.

OutboxUnitOfWork.layer options: auditEnabled (default false), fallbackPrincipalId (default "system"), applicationCode, clientCode. A failed write surfaces as an InfrastructureError with code COMMIT_FAILED.

The tagged errors mirror the neverthrow UseCaseError kinds, with the same code, message and details shape and the same status mapping through httpStatus(error):

Class and tag HTTP
ValidationError 400
AuthorizationError 403
NotFoundError 404
BusinessRuleViolation 409
ConcurrencyError 409
InfrastructureError 500

Fail with Effect.fail(new ValidationError({ code, message })) and match with Effect.catchTag or Effect.catchTags. See Errors.

Both flavours share DomainEvent, BaseDomainEvent, OutboxManager and OutboxDriver, and write the same outbox row, so you can use one flavour in one service and the other in another against the same table, mix them within a service (HTTP calls on the root client, writes through Effect), and migrate use cases one at a time. The platform cannot tell them apart.

TestUnitOfWork.layer(buffer) records emitted events into an array without persisting:

import { Effect } from 'effect';
import { ExecutionContext, TestUnitOfWork, type DomainEvent } from '@flowcatalyst/sdk/effect/usecase';
const recorded: DomainEvent[] = [];
await Effect.runPromise(
new ShipOrderUseCase()
.execute({ orderId: 'ord_1', carrierId: 'ups', trackingNumber: 'X1' })
.pipe(
Effect.provide(TestUnitOfWork.layer(recorded)),
Effect.provideService(ExecutionContext, {
executionId: 'exec-1',
correlationId: 'corr-1',
causationId: null,
principalId: 'test',
initiatedAt: new Date(),
}),
),
);
// recorded.map((e) => e.eventType) is ['orders:fulfillment:order:shipped']

Assert on recorded; a validation failure leaves it empty and fails the effect with the tagged error.