CAITSGet started

A frontend use case

In the frontend, an action goes around a loop. The view publishes an event. The store turns it into a DTO, and sends it to the handler of a use case. The handler calls a port, then publishes the answer as an event. The store reduces it into the state, and the view shows the state.

PRESENTATIONAPPLICATIONDOMAININFRAEventDTOHTTPEventstateUserViewEventBusStoreHandlerMessageBusEntitiesGatewayServer API123456678

A view never calls a handler, and a handler never touches the HTML: events and the store link them. So each one is tested alone. For a first one, follow the tutorial.

The files

A frontend context

src/frontend/messages/
├── event/                              the events, one file each, and MessagesEvent.ts, their union
├── command/add-message/
│   ├── add-message.dto.ts              the input DTO
│   ├── add-message.handler.ts          the handler
│   └── add-message.application.test.ts its tests
├── query/list-messages/                a use case that only reads: the same files
└── presentation/
    ├── MessagesFrontend.ts             what a view of the context gets
    ├── store/messagesStore.ts          the state, and the DTOs to send
    ├── view/message-board/             a view, its test, its stylesheet, its presenter and its loader
    └── component/<component>/          a part that several views place

The domain and the infra hold the entities and the ports, as in the backend: see Ports and adapters.

The steps

  1. Write the events of the use case in event/, one file each, and add them to the union of the context.
  2. Write the tests of the handler: the events it publishes for a DTO. Then the DTO, then the handler.
  3. In the store, send the DTO in send, and reduce the new events in reduce.
  4. Write the test of the view: the DTO that each action sends, the HTML of each state. Then the view.
  5. Place the view on a page: see Pages and routes.

The events

An event is a fact: the user asked for something, or a handler got an answer. Each one is a class, in its own file:

src/frontend/messages/event/MessageAdditionRequested.ts

/** The View publishes it when the user adds a message. */
export class MessageAdditionRequested {
  readonly type = "messages.addition-requested" as const;
  constructor(readonly text: string) {}
}
  • Its type is "<context>.<event>": the class name in kebab case, without the name of the context.
  • <Context>Event.ts is the union of the events of the context. The store reads it.
  • An event is made with new, never as an object literal: the class gets the type and the data right.

The store

The store holds the state of the context. Its file, presentation/store/<context>Store.ts, exports { initialState, reduce, send }:

  • reduce(state, event) gives the new state for each event.
  • send(state, event) gives the DTO that an event asks for, or undefined. CAITS sends it to the handler of its use case. It reads the state as it was before the event: here, it refuses a second change while the first is on its way.

src/frontend/messages/presentation/store/messagesStore.ts

const messagesStore: StoreDefinition<MessagesState, MessagesEvent> = {
  initialState: { messages: { status: "idle" }, change: { status: "idle" } },
  reduce(state, event) {
    switch (event.type) {
      case "messages.requested": return { ...state, messages: { status: "loading" } };
      case "messages.loaded": return { ...state, messages: { status: "loaded", data: event.messages } };
      case "messages.load-failed": return { ...state, messages: { status: "failed", message: event.reason } };
      case "messages.addition-requested": return pending(state, "addition");
      // … the edit and the removal
      case "messages.changed": return { ...state, change: { status: "idle" } };
      // One change at a time: the failure is the one of the change on its way.
      case "messages.change-failed": return state.change.status === "pending" ? { ...state, change: { status: "failed", change: state.change.change, reason: event.reason } } : state;
    }
  },
  send(state, event) {
    if (event.type === "messages.requested" || event.type === "messages.changed") return new ListMessagesQuery();
    if (state.change.status === "pending") return undefined;
    if (event.type === "messages.addition-requested") return new AddMessageCommand(event.text);
    // … the edit and the removal
    return undefined;
  }
};

export default messagesStore;
  • Loadable (@ingenioz-it/caits/state/Loadable) is a value that loads: idle, loading, loaded with its data, or failed with its message.
  • The store is the only place that sends a DTO: a view never imports one.
  • A context has one store at most, and needs one when it has use cases. A store with a state but no use case sends nothing: send: () => undefined.

The type of the frontend, presentation/<Context>Frontend.ts, says what each view gets, and adds the context to Frontends under the name of its folder:

src/frontend/messages/presentation/MessagesFrontend.ts

import type { Frontend } from "@ingenioz-it/caits/state/request";
import type { MessagesEvent } from "#context/event/MessagesEvent.js";
import type { MessagesState } from "./store/messagesStore.js";

/** What a View of the context gets: the events it publishes, and the store it reads. */
export type MessagesFrontend = Frontend<MessagesState, MessagesEvent>;

declare module "@ingenioz-it/caits/di/frontend" {
  interface Frontends { messages: MessagesFrontend }
}

The handler

A frontend handler returns nothing. It calls its ports, then publishes what happened as events of its context. As in the backend, its DTO is a plain class, and the parameter of execute names it.

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

/** The store sends it to the message bus: add a message on the server. */
export class AddMessageCommand {
  constructor(readonly text: string) {}
}

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

import type { EventPublisher } from "@ingenioz-it/caits/messaging/EventPublisher";
import type { MessagesEvent } from "#context/event/MessagesEvent.js";
import { MessagesChanged } from "#context/event/MessagesChanged.js";
import { MessagesChangeFailed } from "#context/event/MessagesChangeFailed.js";
import type { MessagesGateway } from "#context/domain/port/messages-gateway/MessagesGateway.js";
import type { AddMessageCommand } from "./add-message.dto.js";

export class AddMessageHandler {
  constructor(private readonly gateway: MessagesGateway, private readonly events: EventPublisher<MessagesEvent>) {}

  async execute(command: AddMessageCommand): Promise<void> {
    try {
      await this.gateway.add(command.text);
      this.events.publish(new MessagesChanged());
    } catch (error) {
      this.events.publish(new MessagesChangeFailed((error as Error).message));
    }
  }
}

A query works the same way: ListMessagesHandler publishes MessagesLoaded with the messages, or MessagesLoadFailed.

Test the handler

Give a DTO, then name each event that the handler must publish, with expectItToPublish. The order doesn't matter, and other events may come too.

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

import { applicationScenario, describe, expect, test } from "@ingenioz-it/caits/testing/frontend/application";
// … the imports of the events, the entity, the port, the fake and the DTO

describe("add message", () => {
  test("adds the message through the gateway, then announces the change", async ({ app }) => {
    const gateway = app.use(MessagesGateway, new FakeMessagesGateway());

    await applicationScenario(app)
      .givenTheDto(new AddMessageCommand("Hello"))
      .expectItToPublish(new MessagesChanged());

    expect(await gateway.list()).toStrictEqual([new Message("message-1", "Hello")]);
  });

  test("a refusal of the server is announced with its reason", async ({ app }) => {
    app.use(MessagesGateway, new FakeMessagesGateway()).refuseWith("A message cannot be empty.");

    await applicationScenario(app)
      .givenTheDto(new AddMessageCommand(" "))
      .expectItToPublish(new MessagesChangeFailed("A message cannot be empty."));
  });
});

app.get(<Port>) gives the adapter of the test, and app.use(<Port>, fake) swaps in your own: keep it to check it, as the first test does.

The view

A view is a Marko template, in its own folder, presentation/view/<view>/. It takes the frontend of its context with frontendOf($global, "<context>"), publishes an event for each action of the user, and follows the store:

src/frontend/messages/presentation/view/message-board/MessageBoard.marko

<form class="message-board__composer" onSubmit(event) {
  event.preventDefault();
  frontendOf($global, "messages").events.publish(new MessageAdditionRequested(text));
}>
  • follow(store, select, onChange) (@ingenioz-it/caits/state/follow) calls onChange with what select reads of the state, then again at each change.
  • Its presenter, a function next to it, turns the state into what the view shows: the board follows the store with presentMessageBoard.
  • Its loader, a function next to it too, asks for the data of the first HTML. On the server, the page waits for it, so its first HTML holds the messages:

src/frontend/messages/presentation/view/message-board/loadMessageBoard.ts

import { settled } from "@ingenioz-it/caits/state/Loadable";
import { request } from "@ingenioz-it/caits/state/request";
import { MessagesRequested } from "#context/event/MessagesRequested.js";
import type { MessagesFrontend } from "#context/presentation/MessagesFrontend.js";
import { listOf, type MessageList } from "./presentMessageBoard.js";

/** When the board loads, it asks for the messages. On the server, the page then holds them in its HTML. */
export async function loadMessageBoard(frontend: MessagesFrontend): Promise<MessageList> {
  return listOf(await request(frontend, new MessagesRequested(), state => settled(state.messages)));
}

request(frontend, event, until) publishes the event, then waits for until to read a value in the state. The view awaits its loader: <await|initial|=loadMessageBoard(frontendOf($global, "messages"))>.

A view imports no other view. A part that several views share is a component, in presentation/component/<component>/: like a view, it may publish events and read the store. A component that every context places lives in the context shared: see Contexts.

Test the view

A view test checks the two ways of the loop:

  1. Action → DTO. Act on the view, then check the DTO that the store sends.
  2. Event → HTML. Publish the answer of a handler, then check the HTML.

testPresentation("<context>") gives the real event bus and the real store of the context, with a fake message bus: it records each DTO in sent, and runs no handler. This is how you test the store: through its views. A store has no test of its own.

src/frontend/messages/presentation/view/message-board/MessageBoard.test.ts

// @vitest-environment happy-dom
import { afterEach, describe, expect, globalWith, mountTemplate, settle, test, testPresentation } from "@ingenioz-it/caits/testing/frontend/presentation";
// … the imports of the DTOs, the events and the view

afterEach(() => { document.body.innerHTML = ""; });

const setup = () => {
  const presentation = testPresentation("messages");
  const mount = async (answer: MessagesEvent = new MessagesLoaded([])) => {
    const mounted = await mountTemplate(MessageBoard, { $global: globalWith({ messages: presentation }) });
    presentation.events.publish(answer);   // the handler's answer to the view's first request
    await settle();
    presentation.sent.length = 0;          // forget the DTO that the view sent as it loaded
    return mounted;
  };
  return { ...presentation, mount };
};

describe("MessageBoard action → DTO", () => {
  test("adding a message sends its text", async () => {
    const { sent, mount } = setup();
    const { container } = await mount();

    await add(container, "Hello");

    expect(sent).toStrictEqual([new AddMessageCommand("Hello")]);
  });
});

describe("MessageBoard store → HTML", () => {
  test("says why the messages could not be loaded", async () => {
    const { mount } = setup();
    const { container } = await mount(new MessagesLoadFailed("HTTP 503"));

    expect(alerts(container)).toEqual(["The messages could not be loaded: HTTP 503"]);
  });
});
  • The first line runs the test in a page made by happy-dom. settle() waits until the view has drawn the change.
  • add and alerts are helpers of the test file: one submits a message, the other reads the alerts.
  • published lists every event of the bus, in order: read it to check what a view publishes. A context without a store has no sent: its view tests read published.

The rules of the frontend and of use cases check this page.