diff --git a/src/adapters/http/client.ts b/src/adapters/http/client.ts index 209f9c7b..e8721266 100644 --- a/src/adapters/http/client.ts +++ b/src/adapters/http/client.ts @@ -1002,14 +1002,27 @@ async function parseResponse( }; } - // R3-1. V2 treats a 408/425 error envelope as the same server failure as a - // gateway body; the shared status map in contracts is not changed. - const kind = gatewayFailureOr(response.status, statusKind(response.status)); const backendError = envelopeRecord.error && typeof envelopeRecord.error === "object" ? (envelopeRecord.error as Record) : {}; const code = safeBackendCode(envelope); + // 백엔드 1101/02-01 후속. The paired backend answers a field validation + // failure with 400 VALIDATION_FAILED whose details is the field list + // (clean-architecture-backend-template docs/web/http-contract.md §4). It is + // the same failure as a 422, so it gets the same kind and issues and a form + // maps it with the same allowed fields. A 400 VALIDATION_FAILED whose body + // did not parse carries `{cause}`, not a list, and keeps its reading. + const fieldValidation = + response.status === 422 || + (response.status === 400 && + code === "VALIDATION_FAILED" && + Array.isArray(backendError.details)); + // R3-1. V2 treats a 408/425 error envelope as the same server failure as a + // gateway body; the shared status map in contracts is not changed. + const kind = fieldValidation + ? "VALIDATION_REJECTED" + : gatewayFailureOr(response.status, statusKind(response.status)); return { ok: false, error: failure(kind, operation.operationId, attempt, { @@ -1021,10 +1034,9 @@ async function parseResponse( requestId: safeMeta(envelopeRecord.meta).requestId, traceId: safeMeta(envelopeRecord.meta).traceId, retryAfterMs, - validationIssues: - response.status === 422 - ? safeValidationIssues(backendError.details) - : undefined, + validationIssues: fieldValidation + ? safeValidationIssues(backendError.details) + : undefined, }), }; } diff --git a/src/contracts/errors.ts b/src/contracts/errors.ts index 04ad9758..b559cc81 100644 --- a/src/contracts/errors.ts +++ b/src/contracts/errors.ts @@ -1,4 +1,5 @@ import { + MAX_VALIDATION_ISSUE_CANDIDATES, projectValidationIssues, type ValidationIssue, } from "./validation-issues.ts"; @@ -225,14 +226,31 @@ export function withFailureEffect( } /** - * Projects an untrusted 422 details payload into the only validation metadata - * allowed to cross the HTTP boundary. Backend copy and additional values are - * deliberately discarded. + * Projects an untrusted validation details payload into the only validation + * metadata allowed to cross the HTTP boundary. Backend copy and additional + * values are deliberately discarded. * + * 백엔드 1101/02-01 후속. The paired backend's details is the list itself, + * one `{field, code, message}` per violation (its docs/web/http-contract.md + * §4); `field` is read as the path. The scan stays bounded. */ export function safeValidationIssues( value: unknown, ): readonly ValidationIssue[] { + if (Array.isArray(value)) { + return projectValidationIssues( + value + .slice(0, MAX_VALIDATION_ISSUE_CANDIDATES) + .map((entry: unknown) => + entry && typeof entry === "object" + ? { + path: (entry as Readonly>).field, + code: (entry as Readonly>).code, + } + : entry, + ), + ); + } if (!value || typeof value !== "object") return Object.freeze([]); const candidate = value as Readonly<{ issues?: unknown; diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index be1d1bb3..9d4c9277 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -7,7 +7,9 @@ import { createMemoryRouter, RouterProvider, useNavigate } from "react-router-do import { z } from "zod"; import { describe, expect, it, vi } from "vitest"; +import { createHttpClient } from "../../src/adapters/http/client.ts"; import { createFailure } from "../../src/contracts/errors.ts"; +import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts"; import { Button } from "../../src/presentation/components/ui/button.ts"; import { DirtyNavigationDialog, @@ -148,6 +150,66 @@ describe("local form facade", () => { expect(document.body).not.toHaveTextContent("raw-secret-message"); }); + // 백엔드 1101/02-01 후속. The paired backend answers a field validation + // failure with 400 VALIDATION_FAILED and details [{field, code, message}] + // (its docs/web/http-contract.md §4). It reaches the form through the V2 + // client and lands on the same allowed fields a 422 does. + it("maps a paired backend 400 VALIDATION_FAILED onto the form fields", async () => { + const user = userEvent.setup(); + const client = createHttpClient({ + ...TEST_HTTP_CONTRACT, + baseUrl: "https://api.test", + fetcher: async () => + Response.json( + { + success: false, + error: { + code: "VALIDATION_FAILED", + category: "VALIDATION", + message: "요청 값이 올바르지 않습니다.", + retryable: false, + details: [ + { field: "name", code: "NOT_BLANK", message: "raw backend copy" }, + { field: "request", code: "INVALID", message: "raw backend copy" }, + ], + }, + meta: { requestId: "request-1", traceId: "trace-1" }, + }, + { status: 400 }, + ), + }); + render( + { + const result = await client.execute("CREATE_ENTITY", { + body: { name: command.name }, + idempotencyKey: "key-1", + }); + if (result.ok) throw new Error("expected a validation failure"); + return result; + }} + />, + ); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid"); + await user.click(screen.getByRole("button", { name: "Submit" })); + + await waitFor(() => + expect(screen.getByTestId("result")).toHaveTextContent("validation-error"), + ); + expect(screen.getByRole("textbox", { name: /Name/ })).toHaveAttribute( + "aria-invalid", + "true", + ); + expect(screen.getByRole("textbox", { name: /Note/ })).not.toHaveAttribute( + "aria-invalid", + ); + // A class-level error names no form field. + expect(screen.getByRole("alert")).toHaveTextContent( + "서버가 확인하지 못한 입력 항목", + ); + expect(document.body).not.toHaveTextContent("raw backend copy"); + }); + it.each([ [ "AUTH_REQUIRED", diff --git a/tests/integration/http-client.test.ts b/tests/integration/http-client.test.ts index d1a993f6..d640a775 100644 --- a/tests/integration/http-client.test.ts +++ b/tests/integration/http-client.test.ts @@ -616,3 +616,75 @@ describe("envelope keys the paired backend omits", () => { }); }); }); + +// 백엔드 1101/02-01 후속. The paired backend answers a field validation +// failure with 400 VALIDATION_FAILED, details [{field, code, message}] +// (its docs/web/http-contract.md §4): read as the 422 field validation it is. +// Every other 400 keeps its reading. +describe("paired backend 400 VALIDATION_FAILED", () => { + const meta = { requestId: "request-1", traceId: "trace-1" }; + + function answer400(code: string, details?: unknown) { + server.use( + http.post("https://api.test/api/entities", () => + HttpResponse.json( + { + success: false, + error: { + code, + category: "VALIDATION", + message: "요청 값이 올바르지 않습니다.", + retryable: false, + ...(details === undefined ? {} : { details }), + }, + meta, + }, + { status: 400 }, + ), + ), + ); + return testClient({ baseUrl: "https://api.test", clock }).execute( + "CREATE_ENTITY", + { body: { name: "n" }, idempotencyKey: "key-1" }, + ); + } + + it("reads the field details as validation issues, without backend copy", async () => { + const result = await answer400("VALIDATION_FAILED", [ + { field: "name", code: "NOT_BLANK", message: "raw backend copy" }, + { field: "items.name", code: "SIZE", message: "raw backend copy" }, + { field: "request", code: "INVALID", message: "raw backend copy" }, + ]); + + expect(result).toMatchObject({ + ok: false, + error: { + kind: "VALIDATION_REJECTED", + code: "VALIDATION_FAILED", + httpStatus: 400, + retryable: false, + validationIssues: [ + { path: "name", code: "NOT_BLANK" }, + { path: "items.name", code: "SIZE" }, + { path: "request", code: "INVALID" }, + ], + }, + }); + expect(JSON.stringify(result)).not.toContain("raw backend copy"); + }); + + it.each([ + // A body that did not parse: details names the cause, not a field. + { code: "VALIDATION_FAILED", details: { cause: "JsonParseException" } }, + { code: "VALIDATION_FAILED", details: undefined }, + { code: "BAD_PARAMETER", details: { parameter: "limit" } }, + ])("keeps a 400 $code with details $details as before", async ({ code, details }) => { + const result = await answer400(code, details); + + expect(result).toMatchObject({ + ok: false, + error: { kind: "UNKNOWN_CLIENT_FAILURE", code, httpStatus: 400 }, + }); + expect(result.ok ? null : result.error.validationIssues).toBeUndefined(); + }); +});