On this page

Events and workflows

Problem. Creating a user should announce UserCreated, and a duplicate email should be a typed failure, not a generic error.

ts
import {
  dryv,
  event,
  failure,
  field,
  operation,
  property,
  schema,
} from "@dryvcode/author";

const users = dryv.group({ name: "users" });
const values = users.properties({
  Id: property.string.uuid(),
  Email: property.string.email(),
});
const schemas = users.schemas({
  User: schema({ id: field(values.Id).system(), email: field(values.Email) }),
  UserCreatedPayload: schema({ id: field(values.Id) }),
});

// A reacting operation: it receives the event payload
const SendWelcome = operation().input(schemas.UserCreatedPayload);
const reactions = users.operations({ SendWelcome });

// An event with a typed payload, and who listens (an operation or a workflow)
const events = users.events({
  UserCreated: event()
    .payload(schemas.UserCreatedPayload)
    .listeners(reactions.SendWelcome),
});

// A named, typed failure
const failures = users.failures({
  EmailTaken: failure("EMAIL_TAKEN").description(
    "A user with this email already exists",
  ),
});

// The operation that fails with it and announces the event
const CreateUser = operation()
  .role("create")
  .input(schemas.User)
  .output(schemas.User)
  .failures(failures.EmailTaken)
  .emits(events.UserCreated);
users.operations({ CreateUser });

export default dryv.app({ name: "example" }).groups(users);

How packs use this

You declarePacks can generate
.failures(...)Typed error responses, exception classes, documented error codes
.emits(...)Publish calls, outbox rows, event contracts
.listeners(...)Subscribers, consumers, handlers

Workflows

When several operations and events must be sequenced (with conditions and transitions), declare a workflow: named steps, a start step and transitions between them. Workflows reuse existing operations and events; they never redefine them. See Workflows for the full contract and the TypeScript author's workflow(), operationStep, workflowStep and waitFor helpers.

Search in