CAITSGet started

A backend use case

A use case is one thing the app does: add a message, list the messages. In the backend, it lives in one folder, with its DTOs, its handler, its HTTP controller and their tests: a whole endpoint in one place. For a first one, follow the tutorial.

The files

A use case of the backend

src/backend/messages/
├── command/add-message/
│   ├── add-message.dto.ts                       the input DTO and the output DTO
│   ├── add-message.handler.ts                   the handler
│   ├── add-message.application.test.ts          its tests
│   ├── add-message.http.controller.ts           the HTTP controller
│   └── add-message.http.presentation.test.ts    its tests
└── query/list-messages/                         a use case that only reads: the same files
  • command/ holds a use case that changes something, query/ one that only reads.
  • CAITS finds each handler by its file name, and the DTO it handles by the type that its execute takes. You register nothing.
  • A use case imports nothing from another one: what two use cases share goes in the domain. So each one changes, or goes away, alone.

The steps

  1. Create the folder command/<use-case>/ or query/<use-case>/.
  2. Write the tests of the handler, in <use-case>.application.test.ts. Keep npm run tdd running.
  3. Write the DTOs, in <use-case>.dto.ts, then the handler, in <use-case>.handler.ts.
  4. Write the tests of the controller, in <use-case>.http.presentation.test.ts, then the controller, in <use-case>.http.controller.ts.
  5. Add the route, src/routes/_backend/api/…/+handler.ts.
  6. Run npm run check.

The DTOs

A DTO carries data, and nothing else: it is a plain class. The file holds the input DTO, which the use case receives, and the output DTO, its answer.

src/backend/messages/command/add-message/add-message.dto.ts

export class AddMessageCommand {
  constructor(readonly text: string) {}
}

/** The message that was added, as the domain keeps it. */
export class AddMessageOutput {
  constructor(readonly id: string, readonly text: string) {}
}

The handler

One class, whose execute takes the input DTO and returns the output DTO. It asks the domain, then saves through its port:

src/backend/messages/command/add-message/add-message.handler.ts

import { Message } from "#context/domain/entity/Message.js";
import type { MessageRepository } from "#context/domain/port/message-repository/MessageRepository.js";
import { AddMessageOutput, type AddMessageCommand } from "./add-message.dto.js";

export class AddMessageHandler {
  constructor(private readonly messages: MessageRepository) {}

  async execute(command: AddMessageCommand): Promise<AddMessageOutput> {
    const message = Message.create(await this.messages.nextId(), command.text);
    await this.messages.save(message);
    return new AddMessageOutput(message.id, message.text);
  }
}
  • Its constructor names the ports it uses, by type: CAITS gives it the adapters that di.ts binds. See Ports and adapters.
  • The type of the parameter of execute names the DTO it handles: CAITS sends it each AddMessageCommand. Type it even when the handler doesn't read it: execute(_query: ListMessagesQuery).
  • Its return type names its answers, classes of the DTO file. A use case with two answers gives both, Promise<MessageAdded | MessageRefused>, and the controller tells them apart with instanceof.
  • To tell other contexts what happened, it also takes an EventPublisher: see Contexts.
  • It needs the time, or chance? Take a port of your own, such as Clock, with a fake in test.di.ts. CAITS gives no clock.

Test the handler

Give an input DTO, then check the output with expectTheOutputToBe, or the error with expectTheErrorToBe. When the events matter, list them, in order, with expectItToPublish, or check there are none with expectItToPublishNothing. Check what an adapter kept after the scenario.

src/backend/messages/command/add-message/add-message.application.test.ts

import { applicationScenario, describe, expect, test, type TestApplication } from "@ingenioz-it/caits/testing/backend/application";
// … the imports of the domain and of the DTOs

const kept = async (app: TestApplication) => (await app.get(MessageRepository).list()).map(({ id, text }) => [id, text]);

test.for([
  ["", "A message cannot be empty."],
  ["   ", "A message cannot be empty."],
  ["x".repeat(Message.MAX_LENGTH + 1), "A message has at most 280 characters."]
])("the domain refuses %j, and keeps nothing", async ([text, reason], { app }) => {
  await applicationScenario(app)
    .givenTheDto(new AddMessageCommand(text))
    .expectTheErrorToBe(new InvalidMessageError(reason));

  expect(await kept(app)).toEqual([]);
});

app is a backend made for this test alone, with the bindings of test.di.ts over those of di.ts. Its context runs alone: no context map shares its events.

The controller

A controller turns an HTTP request into an input DTO, and the answer into a response. It extends Controller<InputDto, OutputDto>:

  • toDto(request) builds the input DTO from the request. For an invalid request, it throws InvalidInputError: the answer is a 422, and the use case doesn't run.
  • toResponse(output) builds the response.
  • toErrorResponse(error, request) turns the errors of the domain into responses, with problem(…), and passes the others to super. It answers 415 when the body is neither JSON nor a form, 413 above 1 MB, 400 for invalid JSON or an invalid form, 403 for a form that a browser sends from another site, and 500 for any other error, which CAITS reports. A controller that answers an unexpected error in a format of its own reports it with this.reportError(error).

src/backend/messages/command/add-message/add-message.http.controller.ts

import { Controller, InvalidInputError, problem } from "@ingenioz-it/caits/messaging/Controller";
import type { Request } from "@ingenioz-it/caits/messaging/Request";
import { InvalidMessageError } from "#context/domain/error/InvalidMessageError.js";
import { AddMessageCommand, type AddMessageOutput } from "./add-message.dto.js";

/** The body that the API reads: `{ "text": "…" }`. */
const isBody = (body: unknown): body is { text: string } => typeof (body as { text?: unknown } | null)?.text === "string";

/** POST /api/messages: turns the request into an AddMessageCommand, and the output or the error into a response. */
export class AddMessageHttpController extends Controller<AddMessageCommand, AddMessageOutput> {
  protected async toDto(request: Request): Promise<AddMessageCommand> {
    const body = await request.content();
    if (!isBody(body)) throw new InvalidInputError("Invalid body", [{ path: ["text"], message: "The text must be a string." }]);
    return new AddMessageCommand(body.text);
  }

  protected toResponse(output: AddMessageOutput): Response {
    return Response.json(output, { status: 201 });
  }

  protected override toErrorResponse(error: unknown, request: Request): Response | Promise<Response> {
    if (error instanceof InvalidMessageError) return problem(422, "invalid-message", "Invalid message", error.message);
    return super.toErrorResponse(error, request);
  }
}

The errors are application/problem+json responses, with a type such as urn:caits:problem:invalid-message. http in the file name is the name of the controller: a use case can have others, <use-case>.<name>.controller.ts, each with its test.

request is the Request of CAITS: the address, the method, the headers, the signal of a client that leaves, and content(), the content of the body. content() reads the JSON of the body, or a form, multipart/form-data or application/x-www-form-urlencoded, as an object of its fields: a text or a File for each name, a list for a name that comes more than once. It reads 1 MB at most by default, or what content({ maxSize }) says. A browser sends a form from any site without asking the server first, so a form that a browser sends from another site is refused: the browser says so in the header Sec-Fetch-Site. A client that is not a browser, such as curl, sends no such header. The first call reads the body, and the next calls give its content again. A controller never reads the request of the web, whose body can be read only once: controllers-read-the-request-of-caits checks it.

Test the controller

Send a request, check the input DTO that the controller sends, play the answer of the application, and check the response. The message bus is fake: it records the DTOs, and answers what the test says. The request goes through the real route, so the route needs no test.

src/backend/messages/command/add-message/add-message.http.presentation.test.ts

import { describe, expect, presentationScenario, test } from "@ingenioz-it/caits/testing/backend/presentation";
import { AddMessageCommand, AddMessageOutput } from "./add-message.dto.js";

const problemHeaders = { "content-type": "application/problem+json" };

test("hands the text to the application, and answers with the message it added", async ({ app }) => {
  await presentationScenario(app)
    .givenTheRequest("POST", "/api/messages", { text: "Hello" })
    .expectItToSend(new AddMessageCommand("Hello"))
    .givenTheApplicationReplies(new AddMessageOutput("m1", "Hello"))
    .expectTheResponseToBe(201, { id: "m1", text: "Hello" });
});

test("reports an unexpected failure, and tells nothing of it", async ({ app }) => {
  await presentationScenario(app)
    .givenTheRequest("POST", "/api/messages", { text: "Hello" })
    .expectItToSend(new AddMessageCommand("Hello"))
    .givenTheApplicationFails(new Error("disk full"))
    .expectTheResponseToBe(500, { type: "urn:caits:problem:internal-server-error", title: "Internal server error", status: 500 }, problemHeaders);

  expect(app.reportedErrors).toEqual([new Error("disk full")]);
});
  • When the request is invalid, the controller answers at once: the scenario has no expectItToSend.
  • A field that the test cannot know, such as an id that the controller draws, takes a matcher of Vitest in expectItToSend: expect.any(String).
  • An object body goes as JSON, a string as it is, both with content-type: application/json. A FormData goes as a form, with its files, and URLSearchParams as a form of URL encoding. A fourth argument gives headers, which go over the type of the body: .givenTheRequest("POST", "/api/messages", { text: "Hello" }, { authorization: "Bearer abc" }).
  • The headers that a scenario checks take null for a header that the response does not have: { "retry-after": null }.
  • An error that the controller doesn't know becomes a 500 that reveals nothing, and lands in app.reportedErrors.

The route

The route hands the request to the controller, and does nothing else. See Pages and routes.

src/routes/_backend/api/messages/+handler.ts

import { controller } from "@ingenioz-it/caits/di/backend";
import { AddMessageHttpController } from "#backend/messages/command/add-message/add-message.http.controller.js";
import { ListMessagesHttpController } from "#backend/messages/query/list-messages/list-messages.http.controller.js";

export const GET = Run.GET(async (ctx): Promise<Response> => controller(ListMessagesHttpController).handle(ctx.request));

export const POST = Run.POST(async (ctx): Promise<Response> => controller(AddMessageHttpController).handle(ctx.request));

A controller for a timer

Some use cases run on their own while the server runs: a purge, a measure, a check. Their trigger is time, not a request: their controller extends TimerController<InputDto>, in the folder of the use case, as <use-case>.timer.controller.ts.

  • every says how often it runs, in milliseconds: up to 2147483647, about 24 days. The server refuses to start with a longer one, which Node would run every millisecond.
  • toDto() builds the input DTO of each turn.

src/backend/messages/command/purge-messages/purge-messages.timer.controller.ts

import { TimerController } from "@ingenioz-it/caits/messaging/TimerController";
import { PurgeMessagesCommand } from "./purge-messages.dto.js";

/** Every hour, purges the old messages. */
export class PurgeMessagesTimerController extends TimerController<PurgeMessagesCommand> {
  readonly every = 60 * 60 * 1000;

  protected toDto(): PurgeMessagesCommand {
    return new PurgeMessagesCommand();
  }
}

The server of npm start and that of npm run dev run it as soon as they start, each turn in a request of its own, and stop it when they stop. A turn waits for the last one to end. An error of a turn is reported, and the next turn comes anyway. A timer controller has no route. Its handler reads no clock: the time comes from a port, as any time does.

Test it as a controller: run one turn, check the DTO that it sends, and its rhythm.

src/backend/messages/command/purge-messages/purge-messages.timer.presentation.test.ts

import { presentationScenario, test } from "@ingenioz-it/caits/testing/backend/presentation";
import { PurgeMessagesCommand, PurgeMessagesOutput } from "./purge-messages.dto.js";
import { PurgeMessagesTimerController } from "./purge-messages.timer.controller.js";

test("every hour, asks to purge the old messages", async ({ app }) => {
  await presentationScenario(app)
    .givenTheTimer(PurgeMessagesTimerController)
    .expectItToSend(new PurgeMessagesCommand())
    .givenTheApplicationReplies(new PurgeMessagesOutput(2))
    .expectTheTurnToRunEvery(60 * 60 * 1000);
});

A controller that streams

Some answers come piece by piece: the tokens of a language model, the steps of a long task, the news of a feed. Their controller extends StreamController<InputDto, OutputDto>, as <use-case>.stream.controller.ts, and answers with server-sent events, before the handler ends. The handler stays a handler: it publishes the events of its context as they happen, and answers its output at the end. The controller writes them:

  • toDto(request) builds the input DTO, as for a request.
  • toChunk(event) gives the text of an event, with sseEvent(…) or sseComment(…), or nothing to skip it.
  • toOutputChunk(output) gives the text of the output, which ends the stream.
  • follows = "context" makes a feed: the output of the handler, the state at the start, then the events of every request of the context, until the client leaves. The feed listens to the events before it sends the DTO, so that none is lost: an event that comes while the handler reads the state may be in it already. stateHolds(state, event) says so, and the feed does not write it again; it writes each event that comes after the state. By default, a state holds no event. The feed ends when the backend stops, at a docker stop or when npm run dev reloads the code: its client connects again, and gets the state of the next backend. EventSource, in a browser, does it by itself.
  • EventSource connects again to any stream that ends, with the same GET, about 3 seconds later. A feed gives its state again, as it should. A stream of a request would run its use case again and again: its client closes it at the last event (source.close()), or the API takes POST, which EventSource does not send.
  • streams(dto) says whether the request asks for a stream; each one does by default. A request that asks for none gets toResponse(output), the output in JSON by default, once the handler answers, as from a controller. An API that streams or not at the same address, as the body of the request says, has one controller.

When the client leaves, or stops reading, the work it waited for can stop. A controller gives the bus the signal of its request with the DTO, and the handler reads it in its RequestContext, with its correlation id: signal aborts when the client leaves. The handler gives it to the ports whose work the client waits for, which give it to fetch or to their database. A request without a client sees the server stop: the signal of a turn of a timer aborts as soon as the server stops, and that of a reaction to an event once the requests had their 10 seconds, since a reaction often ends the work of a request. In an application test, app.send(dto, { signal }) sends a DTO with the signal of a client that the test makes leave.

src/backend/messages/query/follow-messages/follow-messages.stream.controller.ts

import type { DomainEvent } from "@ingenioz-it/caits/DomainEvent";
import { sseEvent } from "@ingenioz-it/caits/messaging/sse";
import { StreamController } from "@ingenioz-it/caits/messaging/StreamController";
import { MessageAdded } from "#context/domain/event/MessageAdded.js";
import { FollowMessagesQuery, type FollowMessagesOutput } from "./follow-messages.dto.js";

/** GET /api/messages/news: the messages, then each message that someone adds, until the client leaves. */
export class FollowMessagesStreamController extends StreamController<FollowMessagesQuery, FollowMessagesOutput> {
  protected override readonly follows = "context";

  protected toDto(): FollowMessagesQuery {
    return new FollowMessagesQuery();
  }

  protected toChunk(event: DomainEvent): string | undefined {
    return event instanceof MessageAdded ? sseEvent(JSON.stringify({ id: event.id, text: event.text }), { event: "added" }) : undefined;
  }

  protected toOutputChunk(output: FollowMessagesOutput): string {
    return sseEvent(JSON.stringify(output.messages), { event: "messages" });
  }

  /** A message added while the handler read the messages may be among them already. */
  protected override stateHolds(state: FollowMessagesOutput, event: DomainEvent): boolean {
    return event instanceof MessageAdded && state.messages.some(message => message.id === event.id);
  }
}

Until the first event that it writes, or the output, an error is a response, as a controller gives it, with toErrorResponse. An event that it does not write decides nothing, as an event that the handler publishes for another context: the client reads nothing of it. An event that it cannot write is a response too, and the signal of the handler aborts. Once the stream started, an error goes in the stream, with toErrorChunk, and the stream ends. By default, it is an event problem, as CAITS names its errors: an EventSource, in a browser, gives the name error to a connection that fails or ends, and its client would mix the two. This is the same for an error of the controller as it writes the stream, in toChunk, toOutputChunk, stateHolds or the comment that keeps the connection alive: the signal of the handler aborts too, as no one reads what it does next. An error that toErrorChunk cannot write is reported, with the error of toErrorChunk. When the stream says nothing for 15 seconds (keepAliveMs), a comment keeps the connection alive. The headers say text/event-stream, with no cache and no compression that would hold the chunks back.

Test it as a controller: the scenario says what the application publishes, then reads the stream.

src/backend/messages/query/follow-messages/follow-messages.stream.presentation.test.ts

test("gives the messages, then each message that someone adds, once", async ({ app }) => {
  await presentationScenario(app)
    .givenTheRequest("GET", "/api/messages/news")
    .expectItToSend(new FollowMessagesQuery())
    .givenTheApplicationPublishes(new MessageAdded("m1", "Hello"), new MessageAdded("m2", "Hi"))
    .givenTheApplicationReplies(new FollowMessagesOutput([{ id: "m1", text: "Hello" }]))
    .expectTheStreamToStartWith(200, 'event: messages\ndata: [{"id":"m1","text":"Hello"}]\n\nevent: added\ndata: {"id":"m2","text":"Hi"}\n\n');
});

expectTheStreamToBe reads a stream that ends. expectTheStreamToStartWith reads its start, then the client leaves, and checks that the signal that went with each DTO aborted. givenTheApplicationKeepsRunning() keeps the handler from answering.

The rules of use cases and of layers check this page.