Open MercatoDocsSearch docsAPI reference

Framework

Commands framework

A stock adjustment may start in a form today and an import tomorrow. Give both paths one command for validation, the write and its audit record. Decide whether an undo can reconstruct the previous state before offering that operation to users.

The commands framework packages complex write flows into discrete handlers. Commands run inside the request-scoped DI container, emit audit logs, and can capture before/after snapshots for undo.

Key Concepts

Handler Anatomy

import type { CommandHandler } from '@open-mercato/shared/lib/commands'

const createUserCommand: CommandHandler<CreateUserInput, User> = {
  id: 'auth.users.create',
  async execute(input, ctx) {
    // Main mutation logic — runs inside the request container.
  },
  async prepare(input, ctx) {
    // Optional: capture "before" snapshots (e.g., load current record state).
  },
  async captureAfter(input, result, ctx) {
    // Optional: return a serialized post-mutation snapshot for audit logs.
  },
  async buildLog({ input, result, ctx, snapshots }) {
    // Optional: return metadata for ActionLogService (labels, resource ids, etc.).
  },
  async undo({ input, ctx, logEntry }) {
    // Optional: implement reversible operations (requires `isUndoable !== false`).
  },
}

Handler methods are all optional except id and execute. Use the optional hooks when the flow needs richer auditing or undo support. prepare and captureAfter return arbitrary snapshot payloads that are later fed into buildLog.

Registration

Command files register handlers when loaded. The module generator discovers files under commands/ and writes lazy loaders, so module index.ts does not need command side-effect imports:

// packages/core/src/modules/auth/commands/users.ts
import { registerCommand } from '@open-mercato/shared/lib/commands'

registerCommand(createUserCommand)
registerCommand(updateUserCommand)
registerCommand(deleteUserCommand)

The command bus loads the matching command file on demand. Manual imports are still useful in isolated tests that read commandRegistry directly:

import '@open-mercato/core/modules/auth/commands/users'

Attempting to register the same id twice throws an error, helping catch collisions early.

Executing Commands

The request container exposes a singleton CommandBus. Any server entry point with container access (API routes, backend actions, CLI commands, subscribers) can execute a command:

import type { CommandBus } from '@open-mercato/shared/lib/commands'

const commandBus = container.resolve<CommandBus>('commandBus')

await commandBus.execute('auth.users.create', {
  input: { email, password, organizationId },
  ctx: {
    container,
    auth,
    organizationScope,
    selectedOrganizationId,
    organizationIds,
    request,
  },
})

CommandExecutionOptions carries the validated payload plus the runtime context. The context mirrors the request lifecycle, so handlers can pull collaborators (em, dataEngine, services) from the same container instance.

Undo Flow

If a handler implements undo and does not set isUndoable to false, the bus will emit an undoToken in the action log metadata. Later, call commandBus.undo(token, ctx) to reverse the operation. Handlers receive the original input and the persisted log entry, enabling complete restoration.

Auditing & Snapshots

Handlers can opt into structured audit logs by returning metadata from buildLog. The bus merges metadata from the handler, the execution options, and snapshots:

When metadata is provided, the bus writes to ActionLogService (if registered in the container) and persists undo tokens automatically. Snapshot fields (snapshotBefore / snapshotAfter) make it easy to render diffs in the admin UI.

Helper Utilities

Reusable helpers in @open-mercato/shared/lib/commands/helpers cover common patterns:

These helpers keep command files compact while respecting module isolation and extensibility rules.

Testing Commands

Command handlers are ordinary functions and can be tested in isolation. The shared test helpers (packages/shared/src/lib/commands/__tests__/command-bus.test.ts) demonstrate mocking the registry and executing commands through a new CommandBus(). For integration-level tests, instantiate the request container, register the command handler, and execute it via the bus to ensure DI wiring, logging, and undo all work together.

Module Guidelines

Following these practices keeps the command layer consistent, discoverable, and safe to extend as new modules plug into the platform.

Test retries against the business operation

Send the same request twice in a development tenant. For an operation that must happen once, such as issuing a reference or recording a payment, decide how the caller identifies a retry and verify the second attempt cannot duplicate the effect.

Previous: Business rule services · Next: Custom entities (EAV)