ホーム 全セッション S05

キャンセル成功時の値の流れ

8 / 14 目安 1.75分

ページ一覧

解決策: キャンセルが成功する場合に、値が各工程でどう変わるかを参照実装のコードで追跡します。

参照実装はデータベースの応答を待つため ResultAsync を使います。ResultAsync は、データベースの応答を待ってから Ok か Err になる Result です。連結の方法は、記録して返す工程の andThrough を除いて、S04 の Result と同じです。createEvent は Err を返しませんが、ResultAsync を返すため、map ではなく andThen で連結します。

説明用に項目を省略しています。
  1. このコマのコード cancelAppointmentUseCase.ts

    dependencies.userResolver
      .resolveById(input.actorUserId)
      .andThen(ensureUserFound(input.actorUserId))
      .andThen(ensureCanManageClinic)
      .andThen(() =>
        dependencies.appointmentResolver.resolveById(input.appointmentId),
      )
      .andThen(ensureAppointmentFound(input.appointmentId))
      .andThen(ensureCancellable)
      .andThen(createEvent(dependencies, input))
      .andThrough(dependencies.appointmentCanceledStore.store)
      .map((event) => ({ appointment: event.aggregateState }));

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    useCase 全体は、andThen、andThrough、map を連結した1本の連鎖です。実行者の確認、予約の確認、結果を作る、記録して返す、の順に進みます。次のコマから、値の流れを1行ずつ追跡します。

  2. このコマのコード cancellationReason.ts

    const CancellationReasonSchema = z
      .string()
      .trim()
      .min(1)
      .max(500)
      .brand<typeof CancellationReasonBrand>()
      .transform(Sensitive.of);

    受け取る値

    { reason: "owner request" }

    返す値

    { …, reason: "owner request" }

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    useCase の手前の境界が、リクエストを検査します。ここはレールの外です。理由は空ではないため、.min(1) を通過します。

  3. このコマのコード userResolver.ts

    データベースから実行者を取得します。実装は省略します。

    受け取る値

    "(受付担当者の ID)"

    返す値

    Ok({ kind: "Receptionist", … })

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. Ok 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    resolveById が、データベースから実行者を取得します。

  4. このコマのコード errors.ts

    export const ensureUserFound = (
      actorUserId: UserId,
    ) =>
      (user: User | undefined): Result<User, UnauthorizedError> =>
        user === undefined
          ? err({ kind: "Unauthorized", actorUserId })
          : ok(user);

    受け取る値

    { kind: "Receptionist", … }

    返す値

    Ok({ kind: "Receptionist", … })

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. Ok ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    ensureUserFound は、実行者を取得できたため ok を返します。

  5. このコマのコード authorization.ts

    export const ensureCanManageClinic = (
      user: User,
    ): Result<User, UnauthorizedError> =>
      user.kind === "Admin" || user.kind === "Receptionist"
        ? ok(user)
        : err({ kind: "Unauthorized", actorUserId: user.userId });

    受け取る値

    { kind: "Receptionist", … }

    返す値

    Ok({ kind: "Receptionist", … })

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. Ok ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    ensureCanManageClinic が、権限を検証します。Receptionist には権限があります。

  6. このコマのコード appointmentResolver.ts

    データベースから予約を取得します。実装は省略します。

    受け取る値

    "11111111-…"

    返す値

    Ok({ kind: "Scheduled", … })

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. Ok 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    resolveById が、予約を取得します。値は実行者から予約へ変わります。

  7. このコマのコード errors.ts

    export const ensureAppointmentFound = (
      appointmentId: AppointmentId,
    ) =>
      (appointment: Appointment | undefined): Result<Appointment, AppointmentNotFound> =>
        appointment === undefined
          ? err({ kind: "AppointmentNotFound", appointmentId })
          : ok(appointment);

    受け取る値

    { kind: "Scheduled", … }

    返す値

    Ok({ kind: "Scheduled", … })

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. Ok ensureAppointmentFound
    6. ensureCancellable
    7. 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    ensureAppointmentFound は、予約を取得できたため ok を返します。

  8. このコマのコード cancelAppointmentUseCase.ts

    appointment.kind === "Scheduled" || appointment.kind === "CheckedIn"
      ? ok(appointment)
      : err({
          kind: "InvalidAppointmentState",
          appointmentId: appointment.appointmentId,
          expectedKind: "ScheduledOrCheckedIn",
          actualKind: appointment.kind,
        });

    受け取る値

    { kind: "Scheduled", … }

    返す値

    Ok({ kind: "Scheduled", … })

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. Ok ensureCancellable
    7. 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    ensureCancellable が、状態を検証します。Scheduled は診察開始前であるため、ok を返します。err の actualKind は S04 の actual と同じ現在の状態で、expectedKind は通過できる状態です。

  9. このコマのコード cancelAppointmentUseCase.ts

    const createEvent =
      (dependencies: Dependencies, input: UseCaseInput) =>
      (appointment: Scheduled | CheckedIn) =>
        ResultAsync.fromSafePromise(
          Promise.resolve().then(() =>
            Appointment.cancel({
              eventId: dependencies.eventIdGenerator.generate(),
              occurredAt: dependencies.clock.now(),
              actorUserId: input.actorUserId,
            })(appointment, input.reason),

    受け取る値

    { kind: "Scheduled", … }

    返す値

    Ok({ kind: "AppointmentCanceled" })

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. Ok 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    createEvent が、時計から時刻を、ID の生成器から ID を取得し、入力の reason とともに Appointment.cancel へ渡します。前後の工程と同じ ResultAsync の連鎖につなぐために、ResultAsync.fromSafePromise が、処理の結果を、Err にならない ResultAsync に包みます。

  10. このコマのコード appointment.ts

    const aggregateState = {
      kind: "Canceled",
      appointmentId: appointment.appointmentId,
      petId: appointment.petId,
      ownerId: appointment.ownerId,
      scheduledAt: appointment.scheduledAt,
      reason: appointment.reason,
      cancellationReason,
      canceledAt: context.occurredAt,
    } as const satisfies Canceled;

    受け取る値

    予約、"owner request"、context

    返す値

    { kind: "AppointmentCanceled" }

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. Ok 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    Appointment.cancel は、渡された値だけで AppointmentCanceled を作ります。背景で見た3項目が変わり、時刻は context.occurredAt から取ります。

  11. このコマのコード appointmentEventStore.ts

    予約の状態の更新と、イベントの追記を、1回の保存で行います。実装は省略します。

    受け取る値

    { kind: "AppointmentCanceled" }

    返す値

    Ok({ kind: "AppointmentCanceled" })

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. 結果を作る createEvent
    8. Ok 記録して返す andThrough(store)
    9. map
    10. 終点 UseCaseOutput

    andThrough は、Ok の場合だけ store を呼び、値をそのまま次へ渡します。予約の更新とイベントの追記を、1回の保存で行います。

  12. このコマのコード cancelAppointmentUseCase.ts

    .map((event) => ({ appointment: event.aggregateState }));

    受け取る値

    { kind: "AppointmentCanceled" }

    返す値

    Ok({ appointment: { kind: "Canceled" } })

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. Ok map
    10. 終点 UseCaseOutput

    map が、イベントからキャンセル後の予約を取り出します。

  13. このコマのコード cancelAppointmentUseCase.ts

    export type UseCaseError =
      | UnauthorizedError
      | AppointmentNotFound
      | InvalidAppointmentState
      | AppointmentConflict;
    export type UseCaseOutput = UseResultAsync<UseCaseOk, UseCaseError>;

    受け取る値

    { appointment: { kind: "Canceled" } }

    返す値

    Ok({ appointment: { kind: "Canceled" } })

    手前の境界: 入力を検査する レールには乗らない

    成功失敗
    1. 実行者の確認 resolveById
    2. ensureUserFound
    3. ensureCanManageClinic
    4. 予約の確認 resolveById
    5. ensureAppointmentFound
    6. ensureCancellable
    7. 結果を作る createEvent
    8. 記録して返す andThrough(store)
    9. map
    10. Ok 終点 UseCaseOutput

    値は成功レールの終点に到達します。戻り値の型 UseCaseOutput は、成功の型 UseCaseOk と失敗の型 UseCaseError を持つ ResultAsync です(UseResultAsync は別名)。UseCaseError は、工程の失敗のユニオン型です。

確認の問い
  1. 問い: キャンセル前とキャンセル後の予約のデータを比較してください。変わる項目と変わらない項目は、それぞれどれですか。

    答え: appointmentId、scheduledAt、reason は変わりません。kind は Scheduled から Canceled へ変わり、cancellationReason と canceledAt が追加されます。来院理由は reason に保持され、キャンセル理由は cancellationReason に格納されます。