ホーム 全セッション Final

成功の流れで通過する4つの境界

5 / 10 目安 1.25分

ページ一覧

解決策: 課題1に答えます。成功の依頼が通過する4つの境界を確認します。

成功の依頼は、入力の境界から副作用の境界までの4つを通ります。例外の境界は、障害のときだけ通ります。S06 にはない処理として、ログイン中のユーザーと権限の確認が追加されています。別のユースケースで試す場合は、自習のページを参照します。

診察開始の依頼が成功の流れで通過する4つの境界

依頼カードの値が変わり、現在通過している境界の実コードが表示されます。

値は説明用の例です。項目は一部だけを記載しています。

成功

  1. 診察開始の依頼を route の入力の境界で受け取ります。parseBody が HTTP のフォームを読み取り、schema.safeParse が内容を検証します。検証を通過した値だけが、ユースケースの実行(run)に渡す入力(UseCaseInput)になります。
  2. run は検証の関数を andThen でつなぎます。ユーザー、権限、予約の有無、予約が CheckedIn であることを順に検証し、すべて Ok であるため次へ進みます。
  3. Appointment.startExamination が予約を InExamination に遷移させ、ExaminationStarted を生成します。ID と時刻は、ユースケースが port から取得し、context で渡します。
  4. store は transaction の中で、status が CheckedIn の予約の行だけを更新します。
  5. 更新が1行であるため、監査記録のテーブル domainEventsTable に ExaminationStarted を追加します。transaction に渡した関数が最後まで完了すると、状態と監査記録が同時に確定します。
  6. route の match(Result を Ok と Err で分岐する処理)が Ok を受け取り、詳細ページへの 303 リダイレクトを返します。例外の境界は通りません。
  1. 1 入力の境界
  2. 2 業務上の失敗の境界
  3. 3 出力イベントの境界
  4. 4 副作用の境界
  5. 5 例外の境界
  6. 応答

HTTP の入力を検証し、ユースケースの入力へ変換します。

参照実装 examples/final/src/adaptor/primary/web/routes/appointmentRoutes.ts:164, 170, 497
context.req.parseBody(),
…
const parsed = schema.safeParse(body);
  …
  .run({ actorUserId: actor.value.user.userId, appointmentId: appointmentId.value, veterinarianId })
出力 値 UseCaseInput
{
  actorUserId: "u-1",
  appointmentId: "a-1",
  veterinarianId: "v-1",
}

予約なしや状態不正などの業務上の失敗を、型付きの Err として返します。

参照実装 examples/final/src/useCase/startExaminationUseCase.ts:76, 87-91
const run =
      …
      .andThen(ensureUserFound(input.actorUserId))
      .andThen(ensureCanStartExamination(input.veterinarianId))
      .andThen(() => appointmentResolver.resolveById(input.appointmentId))
      .andThen(ensureAppointmentFound(input.appointmentId))
      .andThen(ensureCheckedIn)
参照実装 examples/final/src/useCase/errors.ts:41, 44-47
export const ensureCheckedIn = (
  …
  appointment.kind === "CheckedIn"
    ? ok(appointment)
    : err({
        kind: "InvalidAppointmentState",
        …
出力 Ok CheckedIn
{ kind: "CheckedIn", appointmentId: "a-1", … }
出力 Err InvalidAppointmentState
{
  kind: "InvalidAppointmentState",
  appointmentId: "a-1",
  expectedKind: "CheckedIn",
  actualKind: "InExamination",
}

業務の検証に成功した経路だけが、ExaminationStarted の生成へ進みます。

参照実装 examples/final/src/domain/appointment/appointment.ts:141, 146, 149-151
const startExamination =
  …
  ): ExaminationStarted => {
      kind: "InExamination",
      veterinarianId,
      examinationStartedAt: context.occurredAt,
出力 Ok ExaminationStarted
{
  kind: "ExaminationStarted",
  eventId: "e-1",
  aggregateId: "a-1",
  aggregateState: { kind: "InExamination", … },
  eventName: "appointment.examination-started",
  occurredAt: "2026-08-30T06:30:00.000Z",
}

予約の状態と監査記録を、1つの transaction で保存します。

参照実装 examples/final/src/adaptor/secondary/sqlite/store/appointmentEventStore.ts:145, 148, 173-174, 178
store: (...events: readonly AppointmentProjectionEvent[]) =>
      db.transaction((tx) => {
              …
              case "ExaminationStarted":
                return tx.update(appointmentsTable)
                    …
                    eq(appointmentsTable.status, "CheckedIn"),
参照実装 examples/final/src/adaptor/secondary/sqlite/store/appointmentEventStore.ts:204, 209-210, 216
if (changes !== 1) {
…
}
tx.insert(domainEventsTable)
  …
  .run();
参照実装 examples/final/src/adaptor/secondary/sqlite/store/appointmentEventStore.ts:178, 204-209
          eq(appointmentsTable.status, "CheckedIn"),
…
if (changes !== 1) {
  throw {
    kind: "AppointmentConflict",
    appointmentId: event.aggregateId,
  } as const;
}
参照実装 examples/final/src/adaptor/secondary/sqlite/store/appointmentEventStore.ts:139, 146, 220-222
const AppointmentConflictSchema = z.object({
    …
    ResultAsync.fromPromise<void, AppointmentStoreError>(
      …
      (cause): AppointmentStoreError => {
        const conflict = AppointmentConflictSchema.safeParse(cause);
        if (conflict.success) return conflict.data;
参照実装 examples/final/src/adaptor/secondary/sqlite/store/appointmentEventStore.ts:145, 148, 173-174, 180
store: (...events: readonly AppointmentProjectionEvent[]) =>
      db.transaction((tx) => {
              …
              case "ExaminationStarted":
                return tx.update(appointmentsTable)
                  …
                  .run().changes;
参照実装 examples/final/src/adaptor/secondary/sqlite/store/appointmentEventStore.ts:146, 220-223
ResultAsync.fromPromise<void, AppointmentStoreError>(
  …
  (cause): AppointmentStoreError => {
    const conflict = AppointmentConflictSchema.safeParse(cause);
    if (conflict.success) return conflict.data;
    throw cause;
出力 reject unknown
throw cause;
出力 Err AppointmentConflict
{ kind: "AppointmentConflict", appointmentId: "a-1" }

業務の Result に入らない障害を、共通の境界が受け取って 500 を返します。

参照実装 examples/final/src/app.ts:532-536
app.onError((error) =>
  error instanceof HTTPException
    ? error.getResponse()
    : new Response("Internal Server Error", { status: 500 }),
);
出力 応答 Response
new Response("Internal Server Error", { status: 500 })

route が結果を HTTP の応答に変換します。

参照実装 examples/final/src/adaptor/primary/web/routes/appointmentRoutes.ts:496-501, 506-509
return dependencies.startExamination
  .run({ actorUserId: actor.value.user.userId, appointmentId: appointmentId.value, veterinarianId })
  .match(
    () => context.redirect(detailUrl(appointmentId.value), 303),
    (error) => {
      switch (error.kind) {
        …
        case "InvalidAppointmentState":
          return invalidState(context, appointmentId.value);
        case "AppointmentConflict":
          return context.redirect(`${detailUrl(appointmentId.value)}?error=appointment-conflict`, 303);
出力 応答 Response
context.redirect("/appointments/a-1", 303)
出力 応答 Response
context.redirect("/appointments/a-1?error=invalid-state", 303)
出力 応答 Response
context.redirect("/appointments/a-1?error=appointment-conflict", 303)
出力 応答 Response 例外の境界が作成
new Response("Internal Server Error", { status: 500 })