fix(reference): 샘플 링크를 route ID로 만들고 route 입력 cast를 없앤다 (1101/16-04)
문제: 경로 정본은 계약의 `routes[*].path`인데, 샘플 페이지가 같은 경로를
문자열로 8곳에 다시 적는다(목록 2, 상세 1, 폼 3, 상태 1, 실패 행동 1).
route 입력은 `routeInput.search as ReferenceListFilters`와
`String(route.params.resourceId)`로 cast한다. 계약에서 경로만 바꾸면 tsc는
통과하고 링크는 NOT_FOUND로 간다. 문서(routing-pages-and-patterns 4.2절,
10절 4단계)는 codec 기반 builder와 cast 금지를 권하는데, 샘플이 반대
패턴을 보여 주고 복사되는 기능이 그 습관을 가져간다.
고른 방법: 이미 있는 URL builder를 쓴다.
- `buildRouteUrl(routeId, input, featureCodecs)`(`src/presentation/routes/
route-codecs.ts`)가 route ID로 계약 `path`를 찾고, 라우터가 parse에 쓰는
같은 codec으로 직렬화한다. canonical redirect도 이 함수를 쓴다.
`src/platform`에는 URL builder가 없다. 그래서 플랫폼에 새 공개 헬퍼를
더하지 않았다.
- 기능 쪽 helper는 `presentation/reference-routes.ts`에 둔다.
- `referenceRouteUrl(routeId, input)`: `buildRouteUrl`에 이 기능의
codec을 넘기는 한 줄 래퍼다. routeId는 이 기능 계약의 키로 좁힌다.
- `useReferenceListFilters()`, `useReferenceResourceId()`: 라우터가 이미
통과시킨 route 입력을 같은 codec으로 다시 parse해서 codec의 출력
타입을 얻는다. cast가 없다. 목록 필터는 `useMemo`로 묶어 route 입력이
그대로면 같은 객체를 준다.
- `REFERENCE_FEATURE_ROUTE_CODECS`를 `reference-feature-runtime.ts`에서
새 `presentation/reference-route-codecs.ts`로 옮겼다.
- runtime 파일이 페이지를 lazy import하므로, 페이지 쪽이 runtime 파일에서
codec을 가져오면 순환 의존이 된다.
- codec 표를 helper 파일에 같이 두지 않은 이유: 그러면
`context-routes.ts`가 router의 builder·hook까지 끌어와 초기 JS가
585 B 늘었다(204,809 B로 예산 204,800 B 초과). 분리하면 475 B다.
- `context-routes.ts`와 `reference-contract.test.ts`는 새 위치에서
가져온다.
- 페이지 8곳을 route ID 호출로 바꿨다. 기능 presentation에 `"/examples/`
문자열이 0건, route 입력 cast가 0건이다. 남은 `"/examples/` 4건은 계약의
`path`(정본)다.
- 기능 README에 helper 위치와 쓰는 법을 적었다.
버린 대안:
- 리뷰 (b)처럼 기능 안에 경로 치환·직렬화를 새로 쓰는 헬퍼: 라우터와 같은
일을 두 번 구현한다. 플랫폼 builder가 이미 route ID와 기능 codec을 받는다.
- 리뷰 (c)처럼 `buildRouteUrl`의 input 타입을 route ID별로 좁히기: 플랫폼은
기능 codec 타입을 모른다(15-01 이후 codec은 지연 적재). 라우터 API
변경이라 이 발견 범위를 넘는다.
- 플랫폼 `useRouteInput`을 제네릭으로 바꿔 타입 단언하기: 런타임 검사 없는
단언이라 cast를 다른 이름으로 옮길 뿐이다.
위험·한계:
- 목록 링크가 이제 정식 URL(`/examples/reference-resources?limit=20`)을
가리킨다. 전에는 `?limit` 없는 주소로 갔다가 라우터가 같은 URL로
replace했다. 도착 URL과 history 항목 수는 같다. 폼의 "목록을 새로
불러와 확인" 링크 href 기대값을 이 값으로 바꿨다.
- `buildRouteUrl`은 codec이 거절하는 입력에 예외를 던진다. 백엔드가
공백만 있는 id를 주면(DTO는 `min(1)`, route codec은 trim 후 `min(1)`)
목록 렌더가 기능 오류 경계로 간다. 전에는 링크가 잘못된 주소 화면으로
갔다. DTO와 route codec의 id 규칙 차이는 이 변경 전부터 있다.
- route 입력을 한 번 더 parse한다. 값이 작아 비용은 무시할 만하다.
- 초기 JS gzip이 204,224 B에서 204,699 B로 475 B 늘었다(예산 204,800 B,
여유 576 B → 101 B). 새 코드가 초기 청크에 들어간 것이 아니다.
`route-codecs.ts`는 원래 초기 청크에 있었다. 페이지가 이 모듈을 import하자
rolldown이 `boot` 청크에 있던 것을 공유 청크(`route-input`)로 옮기고,
`route-input`과 `server-state-scope-provider`를 두 청크로 나눴다. 늘어난
양은 청크 분리 비용이다. 예산 값은 바꾸지 않았다.
- 페이지 테스트의 진입 URL 문자열은 그대로 뒀다. 테스트가 경로를 적는
것은 이 발견의 완료 기준 밖이다.
- 상태 페이지의 `(state as ReferenceSupportState)`는 history state 처리라
route 입력 cast가 아니다. 그대로 뒀다.
검증:
- RED(수정 전): 새 `tests/features/reference-feature/
reference-route-links.test.tsx`는 계약의 네 경로를 모두 옮긴(vi.mock)
상태로 목록→상세→목록→폼→목록, 목록→지원 페이지→목록을 걷는다.
2개 모두 실패했다. 상세 링크가 `href=".../items/reference-1"`(기대
`.../entries/reference-1`), 지원 페이지 대신 NOT_FOUND가 나왔다.
- GREEN(수정 후): 같은 테스트 2개 통과. `tests/features/reference-feature`
18 files 89 tests 통과(href 기대값 1곳 변경 뒤).
- 회귀: tests/features, tests/component, tests/architecture, tests/scale,
관련 unit 3개, generator 테스트 81 files 464 tests 통과. 첫 실행에서는
부하(평균 23~35)로 타임아웃 2건(app-build-input,
global-local-independence)이 났고, 단독 재실행과 최종 재실행에서 통과했다.
- 초기 JS gzip(`scripts/build-frontend.ts` 후 check-bundle과 같은 분류로
측정): 수정 전 204,224 B, 수정 후 204,699 B.
- `tsc` app·test·node 통과. 바꾼 파일 `eslint --max-warnings=0` 통과.
- `check-architecture.ts`(pnpm 대신 exec 전용 shim): 381 modules,
순환·위반 없음, rc=0. `verify-documentation-readiness` PASS_SCOPED,
`check-i18n` PASS.
- 페이지 테스트 harness(`renderReference`, `inputWith`)는 새 테스트와
함께 쓰도록 `reference-page-harness.tsx`로 옮겼다. 내용은 그대로다.
Refs: docs/reviews/2026-11-01-maturity-review/16-structure-patterns.md 16-04
This commit is contained in:
@@ -42,6 +42,15 @@ route codec과 URL builder는 `src/presentation/routes/route-codecs.ts`, route t
|
||||
않는다. page는 HTTP client, storage, auth owner, output port나 TanStack API를
|
||||
직접 import하지 않는다.
|
||||
|
||||
page는 경로 문자열을 적지 않는다. 경로는 계약의 `path` 한 곳에만 있다.
|
||||
`presentation/reference-routes.ts`가 다음 helper를 둔다. 이 기능의 route codec은
|
||||
`presentation/reference-route-codecs.ts`에 있다.
|
||||
|
||||
- 링크: `referenceRouteUrl(routeId, { params, search })`. 위 `buildRouteUrl`에
|
||||
이 기능의 codec을 넘긴다.
|
||||
- route 입력: `useReferenceListFilters()`, `useReferenceResourceId()`. 이미
|
||||
통과한 codec으로 다시 읽어 cast 없이 타입을 얻는다.
|
||||
|
||||
## 설치 지점
|
||||
|
||||
feature가 실제 contribution을 소유한다.
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import type { RouteObject } from "react-router-dom";
|
||||
|
||||
import { REFERENCE_FEATURE_CONTRACT } from "./contracts/reference-feature-contract.ts";
|
||||
import {
|
||||
REFERENCE_FEATURE_ROUTE_CODECS,
|
||||
REFERENCE_FEATURE_ROUTE_RUNTIME,
|
||||
} from "./presentation/reference-feature-runtime.ts";
|
||||
import { REFERENCE_FEATURE_ROUTE_RUNTIME } from "./presentation/reference-feature-runtime.ts";
|
||||
import { REFERENCE_FEATURE_ROUTE_CODECS } from "./presentation/reference-route-codecs.ts";
|
||||
|
||||
export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze(
|
||||
Object.values(REFERENCE_FEATURE_CONTRACT.routes).map((definition) => {
|
||||
|
||||
@@ -1,21 +1,9 @@
|
||||
import { lazy } from "react";
|
||||
|
||||
import { REFERENCE_FEATURE_ID } from "../contracts/reference-feature-contract.ts";
|
||||
import {
|
||||
referenceResourceListQuerySchema,
|
||||
referenceResourceParamsSchema,
|
||||
} from "../contracts/reference-schemas.ts";
|
||||
|
||||
/**
|
||||
* 15-01. Route codecs travel with the context routes (`context-routes.ts` puts
|
||||
* them on each route handle), not with the boot-time feature module: zod
|
||||
* schemas are executable and the shell needs none of them before a reference
|
||||
* route is entered.
|
||||
*/
|
||||
export const REFERENCE_FEATURE_ROUTE_CODECS = {
|
||||
ReferenceResourceListQuery: referenceResourceListQuerySchema,
|
||||
ReferenceResourceParams: referenceResourceParamsSchema,
|
||||
} as const;
|
||||
// 16-04. The codecs have their own file: the pages' link helpers need them and
|
||||
// this file lazy-loads the pages, so a page importing it would close a cycle.
|
||||
import { REFERENCE_FEATURE_ROUTE_CODECS } from "./reference-route-codecs.ts";
|
||||
|
||||
export const REFERENCE_FEATURE_ROUTE_RUNTIME = {
|
||||
REFERENCE_RESOURCE_LIST: Object.freeze({
|
||||
|
||||
@@ -4,15 +4,17 @@ import {
|
||||
AsyncSurface,
|
||||
DetailPage,
|
||||
} from "../../../presentation/design-system/index.ts";
|
||||
import { useRouteInput } from "../../../presentation/routes/route-input.tsx";
|
||||
import { useLocale } from "../../../presentation/i18n/index.ts";
|
||||
import {
|
||||
referenceRouteUrl,
|
||||
useReferenceResourceId,
|
||||
} from "./reference-routes.ts";
|
||||
import { useReferenceFailureAction } from "./use-reference-failure-action.ts";
|
||||
import { useReferenceDetail } from "./use-reference-feature.ts";
|
||||
|
||||
export default function ReferenceResourceDetailPage() {
|
||||
const { date, message } = useLocale();
|
||||
const route = useRouteInput();
|
||||
const resourceId = String(route.params.resourceId);
|
||||
const resourceId = useReferenceResourceId();
|
||||
const { query } = useReferenceDetail(resourceId);
|
||||
const resource = query.data;
|
||||
const failureAction = useReferenceFailureAction(query.state.failure);
|
||||
@@ -21,7 +23,7 @@ export default function ReferenceResourceDetailPage() {
|
||||
<DetailPage
|
||||
key={resourceId}
|
||||
breadcrumb={
|
||||
<Link to="/examples/reference-resources">
|
||||
<Link to={referenceRouteUrl("REFERENCE_RESOURCE_LIST")}>
|
||||
{message("reference.list.resources")}
|
||||
</Link>
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
toCreateReferenceCommand,
|
||||
type ReferenceResourceFormValues,
|
||||
} from "./reference-resource-form.ts";
|
||||
import { referenceRouteUrl } from "./reference-routes.ts";
|
||||
import { useReferenceFailureAction } from "./use-reference-failure-action.ts";
|
||||
import { useReferenceCreate } from "./use-reference-feature.ts";
|
||||
|
||||
@@ -71,7 +72,7 @@ export default function ReferenceResourceFormPage() {
|
||||
<button
|
||||
className="ui-button ui-button--ghost"
|
||||
type="button"
|
||||
onClick={() => navigate("/examples/reference-resources")}
|
||||
onClick={() => navigate(referenceRouteUrl("REFERENCE_RESOURCE_LIST"))}
|
||||
>
|
||||
{message("reference.form.back")}
|
||||
</button>
|
||||
@@ -111,7 +112,7 @@ export default function ReferenceResourceFormPage() {
|
||||
<FormActions sticky>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => navigate("/examples/reference-resources")}
|
||||
onClick={() => navigate(referenceRouteUrl("REFERENCE_RESOURCE_LIST"))}
|
||||
disabled={form.pending || mutationBlocked}
|
||||
>
|
||||
{message("reference.form.cancel")}
|
||||
@@ -159,7 +160,7 @@ export default function ReferenceResourceFormPage() {
|
||||
/>
|
||||
<p>
|
||||
<Link
|
||||
to="/examples/reference-resources"
|
||||
to={referenceRouteUrl("REFERENCE_RESOURCE_LIST")}
|
||||
onClick={() => {
|
||||
void invalidation
|
||||
?.invalidate([REFERENCE_RESOURCE_INVALIDATION_TOPIC])
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
CollectionPage,
|
||||
} from "../../../presentation/design-system/index.ts";
|
||||
import { useLocale } from "../../../presentation/i18n/index.ts";
|
||||
import { referenceRouteUrl } from "./reference-routes.ts";
|
||||
import { useReferenceFailureAction } from "./use-reference-failure-action.ts";
|
||||
import { useReferenceFeature } from "./use-reference-feature.ts";
|
||||
|
||||
@@ -26,7 +27,7 @@ export default function ReferenceResourcePage() {
|
||||
{
|
||||
kind: "button",
|
||||
label: message("reference.list.create"),
|
||||
onAction: () => navigate("/examples/reference-resources/new"),
|
||||
onAction: () => navigate(referenceRouteUrl("REFERENCE_RESOURCE_FORM")),
|
||||
},
|
||||
]}
|
||||
activeFilters={
|
||||
@@ -63,7 +64,9 @@ export default function ReferenceResourcePage() {
|
||||
{(query.data ?? []).map((resource) => (
|
||||
<li key={resource.resourceId}>
|
||||
<Link
|
||||
to={`/examples/reference-resources/items/${encodeURIComponent(resource.resourceId)}`}
|
||||
to={referenceRouteUrl("REFERENCE_RESOURCE_DETAIL", {
|
||||
params: { resourceId: resource.resourceId },
|
||||
})}
|
||||
>
|
||||
{resource.title}
|
||||
</Link>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useLocation, useNavigate } from "react-router-dom";
|
||||
|
||||
import { StatusPage } from "../../../presentation/design-system/index.ts";
|
||||
import { useLocale } from "../../../presentation/i18n/index.ts";
|
||||
import { referenceRouteUrl } from "./reference-routes.ts";
|
||||
import type { ReferenceSupportState } from "./use-reference-failure-action.ts";
|
||||
|
||||
/** History state is untrusted input: only a string reference is shown. */
|
||||
@@ -31,7 +32,7 @@ export default function ReferenceResourceStatusPage() {
|
||||
primaryAction={{
|
||||
kind: "button",
|
||||
label: message("reference.status.back"),
|
||||
onAction: () => navigate("/examples/reference-resources"),
|
||||
onAction: () => navigate(referenceRouteUrl("REFERENCE_RESOURCE_LIST")),
|
||||
}}
|
||||
supportReference={supportReference}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import {
|
||||
referenceResourceListQuerySchema,
|
||||
referenceResourceParamsSchema,
|
||||
} from "../contracts/reference-schemas.ts";
|
||||
|
||||
/**
|
||||
* 15-01. Route codecs travel with the context routes (`context-routes.ts` puts
|
||||
* them on each route handle), not with the boot-time feature module: zod
|
||||
* schemas are executable and the shell needs none of them before a reference
|
||||
* route is entered. 16-04: the pages' link helpers (`reference-routes.ts`) use
|
||||
* them too; this file imports no router code, so loading the context routes
|
||||
* does not pull in the link builder.
|
||||
*/
|
||||
export const REFERENCE_FEATURE_ROUTE_CODECS = {
|
||||
ReferenceResourceListQuery: referenceResourceListQuerySchema,
|
||||
ReferenceResourceParams: referenceResourceParamsSchema,
|
||||
} as const;
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { buildRouteUrl } from "../../../presentation/routes/route-codecs.ts";
|
||||
import { useRouteInput } from "../../../presentation/routes/route-input.tsx";
|
||||
import type { ReferenceListFilters } from "../application/reference-feature-api.ts";
|
||||
import type { REFERENCE_FEATURE_CONTRACT } from "../contracts/reference-feature-contract.ts";
|
||||
import { REFERENCE_FEATURE_ROUTE_CODECS } from "./reference-route-codecs.ts";
|
||||
|
||||
/**
|
||||
* 16-04. A reference link names its route ID. The router's own builder fills
|
||||
* in the contract's `path` through the codecs that parse it, so the contract
|
||||
* stays the one place a path is written.
|
||||
*/
|
||||
export function referenceRouteUrl(
|
||||
routeId: keyof typeof REFERENCE_FEATURE_CONTRACT.routes,
|
||||
input?: Parameters<typeof buildRouteUrl>[1],
|
||||
): string {
|
||||
return buildRouteUrl(routeId, input, REFERENCE_FEATURE_ROUTE_CODECS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 16-04. The router hands pages untyped route input. Reading it back through
|
||||
* the codec that already accepted it gives the codec's type without a cast.
|
||||
*/
|
||||
export function useReferenceListFilters(): ReferenceListFilters {
|
||||
const { search } = useRouteInput();
|
||||
return useMemo(
|
||||
() => REFERENCE_FEATURE_ROUTE_CODECS.ReferenceResourceListQuery.parse(search),
|
||||
[search],
|
||||
);
|
||||
}
|
||||
|
||||
export function useReferenceResourceId(): string {
|
||||
return REFERENCE_FEATURE_ROUTE_CODECS.ReferenceResourceParams.parse(
|
||||
useRouteInput().params,
|
||||
).resourceId;
|
||||
}
|
||||
@@ -3,8 +3,7 @@ import { useLocation, useNavigate } from "react-router-dom";
|
||||
|
||||
import type { AppFailure } from "../../../contracts/errors.ts";
|
||||
import { useSession } from "../../../presentation/providers/session-provider.tsx";
|
||||
|
||||
const REFERENCE_SUPPORT_ROUTE = "/examples/reference-resources/status";
|
||||
import { referenceRouteUrl } from "./reference-routes.ts";
|
||||
|
||||
/** 0929/08-04. What the support status page receives as navigation state. */
|
||||
export type ReferenceSupportState = Readonly<{ supportReference?: string }>;
|
||||
@@ -38,7 +37,7 @@ export function useReferenceFailureAction(
|
||||
// The id stays in history state, never in the URL.
|
||||
const state: ReferenceSupportState =
|
||||
requestId === undefined ? {} : { supportReference: requestId };
|
||||
void navigate(REFERENCE_SUPPORT_ROUTE, { state });
|
||||
void navigate(referenceRouteUrl("REFERENCE_RESOURCE_STATUS"), { state });
|
||||
}
|
||||
}, [
|
||||
action,
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
useApplicationMutation,
|
||||
useApplicationQuery,
|
||||
} from "../../../presentation/adapters/query/application-query.ts";
|
||||
import { useRouteInput } from "../../../presentation/routes/route-input.tsx";
|
||||
import {
|
||||
REFERENCE_FEATURE_ID,
|
||||
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
||||
@@ -21,6 +20,7 @@ import {
|
||||
type QueryResultMeasure,
|
||||
} from "../../../contracts/server-state.ts";
|
||||
import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx";
|
||||
import { useReferenceListFilters } from "./reference-routes.ts";
|
||||
|
||||
const UTF8 = new TextEncoder();
|
||||
|
||||
@@ -114,8 +114,7 @@ export function useReferenceCreate() {
|
||||
export function useReferenceFeature() {
|
||||
const input = useReferenceFeatureInput();
|
||||
const scope = useServerStateScope();
|
||||
const routeInput = useRouteInput();
|
||||
const filters = routeInput.search as ReferenceListFilters;
|
||||
const filters = useReferenceListFilters();
|
||||
const query = useApplicationQuery(
|
||||
bindQuery(
|
||||
{
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
||||
} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
|
||||
import { REFERENCE_API_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-api-contract.ts";
|
||||
import { REFERENCE_FEATURE_ROUTE_CODECS } from "../../../src/features/reference-feature/presentation/reference-feature-runtime.ts";
|
||||
import { REFERENCE_FEATURE_ROUTE_CODECS } from "../../../src/features/reference-feature/presentation/reference-route-codecs.ts";
|
||||
import type { ReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts";
|
||||
import { createTestApplication } from "../../helpers/create-test-application.ts";
|
||||
import { createReferenceFeatureInstalledInput } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts";
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import {
|
||||
QueryClient,
|
||||
QueryClientProvider,
|
||||
} from "@tanstack/react-query";
|
||||
import { render } from "@testing-library/react";
|
||||
|
||||
import { createDemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts";
|
||||
import type { AuthSessionPort } from "../../../src/application/ports/auth-session-port.ts";
|
||||
import type { MutationIntentFactory } from "../../../src/application/ports/mutation-intent-factory.ts";
|
||||
import type { ReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts";
|
||||
import { REFERENCE_FEATURE_ID } from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
|
||||
import type { QueryInvalidationCoordinator } from "../../../src/contracts/query-invalidation.ts";
|
||||
import { QueryInvalidationProvider } from "../../../src/presentation/adapters/query/query-invalidation-provider.tsx";
|
||||
import { MutationIntentProvider } from "../../../src/presentation/adapters/query/mutation-intent-provider.tsx";
|
||||
import { ServerStateScopeProvider } from "../../../src/presentation/adapters/query/server-state-scope-provider.tsx";
|
||||
import { createServerStateScopeRuntime } from "../../../src/adapters/query-cache/server-state-scope-runtime.ts";
|
||||
import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx";
|
||||
import { PreferenceProviders } from "../../../src/presentation/providers/preference-providers.tsx";
|
||||
import { AppRouter } from "../../../src/presentation/routes/app-router.tsx";
|
||||
import { createTestApplication } from "../../helpers/create-test-application.ts";
|
||||
|
||||
/** The real router with the providers the reference pages read. */
|
||||
export function renderReference(
|
||||
input: ReferenceFeatureInput,
|
||||
url = "/examples/reference-resources?limit=5",
|
||||
session: AuthSessionPort = createDemoSessionAdapter("authenticated"),
|
||||
) {
|
||||
window.history.pushState({}, "", url);
|
||||
const client = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false, gcTime: Infinity },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
const invalidation: QueryInvalidationCoordinator = Object.freeze({
|
||||
async invalidate() {},
|
||||
beginMutation() {
|
||||
return Object.freeze({
|
||||
async release() {},
|
||||
});
|
||||
},
|
||||
async resetLocal() {},
|
||||
dispose() {},
|
||||
});
|
||||
const serverStateScope = createServerStateScopeRuntime({
|
||||
session,
|
||||
queryInvalidation: invalidation,
|
||||
});
|
||||
let intentSequence = 0;
|
||||
const mutationIntentFactory: MutationIntentFactory = Object.freeze({
|
||||
create(input) {
|
||||
intentSequence += 1;
|
||||
return Object.freeze({
|
||||
intentId: `reference-page-intent-${intentSequence}`,
|
||||
operationId: input.operationId,
|
||||
canonicalInputIdentity: input.canonicalInputIdentity,
|
||||
...(input.requiresIdempotencyKey
|
||||
? { idempotencyKey: `reference-page-key-${intentSequence}` }
|
||||
: {}),
|
||||
createdAtMonotonicMs: intentSequence,
|
||||
});
|
||||
},
|
||||
});
|
||||
return Object.assign(render(
|
||||
<MutationIntentProvider factory={mutationIntentFactory}>
|
||||
<QueryClientProvider client={client}>
|
||||
<ServerStateScopeProvider runtime={serverStateScope}>
|
||||
<QueryInvalidationProvider coordinator={invalidation}>
|
||||
<ApplicationProvider
|
||||
application={createTestApplication({
|
||||
session,
|
||||
featureInputs: { [REFERENCE_FEATURE_ID]: input },
|
||||
})}
|
||||
>
|
||||
<PreferenceProviders>
|
||||
<AppRouter />
|
||||
</PreferenceProviders>
|
||||
</ApplicationProvider>
|
||||
</QueryInvalidationProvider>
|
||||
</ServerStateScopeProvider>
|
||||
</QueryClientProvider>
|
||||
</MutationIntentProvider>,
|
||||
), { client });
|
||||
}
|
||||
|
||||
export function inputWith(
|
||||
overrides: Partial<ReferenceFeatureInput> = {},
|
||||
): ReferenceFeatureInput {
|
||||
return {
|
||||
listResources: async () => ({ ok: true, value: [] }),
|
||||
createResource: async ({ name }) => ({
|
||||
ok: true,
|
||||
value: {
|
||||
resourceId: "created",
|
||||
title: name,
|
||||
createdAt: null,
|
||||
},
|
||||
}),
|
||||
getResource: async (resourceId) => ({
|
||||
ok: true,
|
||||
value: {
|
||||
resourceId,
|
||||
title: "Detail",
|
||||
createdAt: null,
|
||||
},
|
||||
}),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -1,126 +1,23 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import {
|
||||
QueryClient,
|
||||
QueryClientProvider,
|
||||
} from "@tanstack/react-query";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createDemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts";
|
||||
import type { AuthSessionPort } from "../../../src/application/ports/auth-session-port.ts";
|
||||
import type { MutationIntentFactory } from "../../../src/application/ports/mutation-intent-factory.ts";
|
||||
import type {
|
||||
ReferenceFeatureInput,
|
||||
ReferenceResult,
|
||||
} from "../../../src/features/reference-feature/application/reference-feature-api.ts";
|
||||
import {
|
||||
REFERENCE_FEATURE_ID,
|
||||
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
||||
REFERENCE_RESOURCE_QUERY_NAMESPACE,
|
||||
} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
|
||||
import { INVALIDATION_REGISTRY } from "../../../src/features/installed-feature-contracts.ts";
|
||||
import type { ReferenceResourceView } from "../../../src/features/reference-feature/contracts/reference-mapper.ts";
|
||||
import { createFailure } from "../../../src/contracts/errors.ts";
|
||||
import type { QueryInvalidationCoordinator } from "../../../src/contracts/query-invalidation.ts";
|
||||
import { QueryInvalidationProvider } from "../../../src/presentation/adapters/query/query-invalidation-provider.tsx";
|
||||
import { MutationIntentProvider } from "../../../src/presentation/adapters/query/mutation-intent-provider.tsx";
|
||||
import { ServerStateScopeProvider } from "../../../src/presentation/adapters/query/server-state-scope-provider.tsx";
|
||||
import { createServerStateScopeRuntime } from "../../../src/adapters/query-cache/server-state-scope-runtime.ts";
|
||||
import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx";
|
||||
import { PreferenceProviders } from "../../../src/presentation/providers/preference-providers.tsx";
|
||||
import { AppRouter } from "../../../src/presentation/routes/app-router.tsx";
|
||||
import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts";
|
||||
import { createTestApplication } from "../../helpers/create-test-application.ts";
|
||||
|
||||
function renderReference(
|
||||
input: ReferenceFeatureInput,
|
||||
url = "/examples/reference-resources?limit=5",
|
||||
session: AuthSessionPort = createDemoSessionAdapter("authenticated"),
|
||||
) {
|
||||
window.history.pushState({}, "", url);
|
||||
const client = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false, gcTime: Infinity },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
const invalidation: QueryInvalidationCoordinator = Object.freeze({
|
||||
async invalidate() {},
|
||||
beginMutation() {
|
||||
return Object.freeze({
|
||||
async release() {},
|
||||
});
|
||||
},
|
||||
async resetLocal() {},
|
||||
dispose() {},
|
||||
});
|
||||
const serverStateScope = createServerStateScopeRuntime({
|
||||
session,
|
||||
queryInvalidation: invalidation,
|
||||
});
|
||||
let intentSequence = 0;
|
||||
const mutationIntentFactory: MutationIntentFactory = Object.freeze({
|
||||
create(input) {
|
||||
intentSequence += 1;
|
||||
return Object.freeze({
|
||||
intentId: `reference-page-intent-${intentSequence}`,
|
||||
operationId: input.operationId,
|
||||
canonicalInputIdentity: input.canonicalInputIdentity,
|
||||
...(input.requiresIdempotencyKey
|
||||
? { idempotencyKey: `reference-page-key-${intentSequence}` }
|
||||
: {}),
|
||||
createdAtMonotonicMs: intentSequence,
|
||||
});
|
||||
},
|
||||
});
|
||||
return Object.assign(render(
|
||||
<MutationIntentProvider factory={mutationIntentFactory}>
|
||||
<QueryClientProvider client={client}>
|
||||
<ServerStateScopeProvider runtime={serverStateScope}>
|
||||
<QueryInvalidationProvider coordinator={invalidation}>
|
||||
<ApplicationProvider
|
||||
application={createTestApplication({
|
||||
session,
|
||||
featureInputs: { [REFERENCE_FEATURE_ID]: input },
|
||||
})}
|
||||
>
|
||||
<PreferenceProviders>
|
||||
<AppRouter />
|
||||
</PreferenceProviders>
|
||||
</ApplicationProvider>
|
||||
</QueryInvalidationProvider>
|
||||
</ServerStateScopeProvider>
|
||||
</QueryClientProvider>
|
||||
</MutationIntentProvider>,
|
||||
), { client });
|
||||
}
|
||||
|
||||
function inputWith(
|
||||
overrides: Partial<ReferenceFeatureInput> = {},
|
||||
): ReferenceFeatureInput {
|
||||
return {
|
||||
listResources: async () => ({ ok: true, value: [] }),
|
||||
createResource: async ({ name }) => ({
|
||||
ok: true,
|
||||
value: {
|
||||
resourceId: "created",
|
||||
title: name,
|
||||
createdAt: null,
|
||||
},
|
||||
}),
|
||||
getResource: async (resourceId) => ({
|
||||
ok: true,
|
||||
value: {
|
||||
resourceId,
|
||||
title: "Detail",
|
||||
createdAt: null,
|
||||
},
|
||||
}),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
import { inputWith, renderReference } from "./reference-page-harness.tsx";
|
||||
|
||||
/**
|
||||
* 0929/08-02. The main area's text and accessible names with every ko-KR
|
||||
@@ -489,9 +386,11 @@ describe("reference feature page states", () => {
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "변경되지 않음으로 확인" }),
|
||||
).not.toBeInTheDocument();
|
||||
// 16-04. Built by the route codec, so the link is already the canonical
|
||||
// URL the router would redirect to (the default limit is written out).
|
||||
expect(
|
||||
screen.getByRole("link", { name: "목록을 새로 불러와 확인" }),
|
||||
).toHaveAttribute("href", "/examples/reference-resources");
|
||||
).toHaveAttribute("href", "/examples/reference-resources?limit=20");
|
||||
await user.click(screen.getByRole("button", { name: "저장" }));
|
||||
expect(createResource).toHaveBeenCalledOnce();
|
||||
expect(name).toHaveValue("Unknown result");
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type * as ReferenceContractModule from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
|
||||
import { createFailure } from "../../../src/contracts/errors.ts";
|
||||
import { inputWith, renderReference } from "./reference-page-harness.tsx";
|
||||
|
||||
/**
|
||||
* 1101/16-04. The contract's `path` is the only place a reference path is
|
||||
* written. Every path is moved here, so a page that writes its own path
|
||||
* string lands on the not-found page instead of the moved route.
|
||||
*/
|
||||
vi.mock(
|
||||
"../../../src/features/reference-feature/contracts/reference-feature-contract.ts",
|
||||
async (importOriginal) => {
|
||||
const original = await importOriginal<typeof ReferenceContractModule>();
|
||||
const contract = original.REFERENCE_FEATURE_CONTRACT;
|
||||
const moved = (
|
||||
routeId: keyof typeof contract.routes,
|
||||
path: string,
|
||||
) => Object.freeze({ ...contract.routes[routeId], path });
|
||||
return {
|
||||
...original,
|
||||
REFERENCE_FEATURE_CONTRACT: Object.freeze({
|
||||
...contract,
|
||||
routes: Object.freeze({
|
||||
REFERENCE_RESOURCE_LIST: moved(
|
||||
"REFERENCE_RESOURCE_LIST",
|
||||
"/examples/reference-resources/all",
|
||||
),
|
||||
REFERENCE_RESOURCE_DETAIL: moved(
|
||||
"REFERENCE_RESOURCE_DETAIL",
|
||||
"/examples/reference-resources/entries/:resourceId",
|
||||
),
|
||||
REFERENCE_RESOURCE_FORM: moved(
|
||||
"REFERENCE_RESOURCE_FORM",
|
||||
"/examples/reference-resources/create",
|
||||
),
|
||||
REFERENCE_RESOURCE_STATUS: moved(
|
||||
"REFERENCE_RESOURCE_STATUS",
|
||||
"/examples/reference-resources/support",
|
||||
),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const LIST = "/examples/reference-resources/all?limit=5";
|
||||
const LIST_HEADING = { level: 1, name: "참조 기능" } as const;
|
||||
|
||||
describe("reference links follow the contract paths", () => {
|
||||
it("moves between list, detail and form through the contract", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderReference(
|
||||
inputWith({
|
||||
listResources: async () => ({
|
||||
ok: true,
|
||||
value: [{ resourceId: "reference-1", title: "Loaded", createdAt: null }],
|
||||
}),
|
||||
}),
|
||||
LIST,
|
||||
);
|
||||
|
||||
const item = await screen.findByRole("link", { name: "Loaded" });
|
||||
expect(item).toHaveAttribute(
|
||||
"href",
|
||||
"/examples/reference-resources/entries/reference-1",
|
||||
);
|
||||
await user.click(item);
|
||||
await screen.findByText("Detail");
|
||||
await user.click(screen.getByRole("link", { name: "참조 리소스 목록" }));
|
||||
await screen.findByRole("heading", LIST_HEADING);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "새 항목 만들기" }));
|
||||
await screen.findByRole("heading", { name: "Reference resource 만들기" });
|
||||
await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" }));
|
||||
expect(await screen.findByRole("heading", LIST_HEADING)).toBeVisible();
|
||||
});
|
||||
|
||||
it("opens the support page and returns to the list through the contract", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderReference(
|
||||
inputWith({
|
||||
listResources: async () => ({
|
||||
ok: false,
|
||||
error: createFailure(
|
||||
"UNKNOWN_CLIENT_FAILURE",
|
||||
"LIST_REFERENCE_RESOURCES",
|
||||
0,
|
||||
{ requestId: "corr-moved" },
|
||||
),
|
||||
}),
|
||||
}),
|
||||
LIST,
|
||||
);
|
||||
|
||||
await user.click(await screen.findByRole("button", { name: "지원 정보 확인" }));
|
||||
expect(
|
||||
await screen.findByRole("heading", { level: 1, name: "잠시 사용할 수 없습니다." }),
|
||||
).toBeVisible();
|
||||
await user.click(screen.getByRole("button", { name: "목록으로 이동" }));
|
||||
expect(await screen.findByRole("heading", LIST_HEADING)).toBeVisible();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user