앞 커밋(1112/01-01) 뒤 확인 리뷰가 완료 기준의 남은 셋과 결함 둘을 찾았다. - 생성 작성 페이지에 마운트 표시(useRef)와 저장 뒤 이동이 남았다. 저장이 끝나면 페이지가 폼보다 먼저, 폼이 pending인 동안 상세로 옮겼다. 다시 마운트한 폼에서 재전송이 성공하면 사용자가 돌아와 입력한, 보낸 적 없는 값을 이탈 확인 없이 버렸다(1112/01-02 영향). - 폼이 재전송 결과로 결과 불명을 다시 판정했다(resendLeftUnknown). 코디네이터와 401에서 갈린다. 코디네이터는 결과 불명을 쥐고 폼은 다시 로그인으로 가는데, FormSaveFeedback이 결과 불명을 먼저 그려 다시 로그인 안내를 가렸다(D-2 위반). - 지난 세 결함(1105/08-02·08-04, 1106/08-02)의 시험이 생성 페이지 시험에만 있었다. 고른 방법: useAppForm에 onSaved를 더한다(추가만). 폼이 결과를 보이고 pending을 끈 뒤, 마운트된 동안만 부른다. confirmUnknownEffect(then)도 마운트된 동안만 then을 부른다. resendUnknownEffect의 then 인자와 FormSaveFeedback의 onResent는 지운다(앞 커밋에서 생겨 아직 내보낸 적이 없다). 재전송 뒤 결과 불명인지는 코디네이터의 새 holdsUnknownEffect로 묻는다. mutation 없이 쓰는 폼(이미 생성한 페이지)은 물을 곳이 없어 같은 거절 표(isRefusedOnEveryAttempt)로 본다. FormSaveFeedback은 다시 로그인 실패를 결과 불명보다 먼저 그린다. 생성 페이지는 mutation.submit을 그대로 넘기고 onSaved와 onConfirmed에서 옮기기만 한다. VD-04 머리 칸에 넣었던 문장은 보완 절로 옮긴다(머리 칸의 백틱 낱말을 문서 검사가 경로로 본다). 페이지가 FormSaveFeedback을 늘 넘기므로, 할 말이 없는 피드백 칸은 자리를 차지하지 않는다(templates.css, 빈 칸이 그리드 간격을 한 줄 더했다). 위험·한계: 저장 뒤 이동이 폼이 결과를 그린 뒤로 한 번 늦어진다. 다시 마운트한 폼에 보내지 않은 값이 있으면 이동이 이탈 확인을 띄운다(의도). 검증: form-foundation 새 시험 일곱과 create-feature 생성 페이지 시험 (RED·GREEN, 막기·다른 저장·충돌 안내 변이 셋), 생성 기능 e2e의 피드백 칸 간격 시험은 desktop에서 돌려 PR 본문에 적는다. Refs: 1112/01-01, 1112/01-02, 1105/08-02, 1105/08-04, 1106/08-02, 1112/04-02
1099 lines
39 KiB
TypeScript
1099 lines
39 KiB
TypeScript
/**
|
|
* 1103/09-06, 03-07. The `--with-create` slice of `pnpm create:feature`: the
|
|
* paired backend scaffold's other two endpoints
|
|
* (clean-architecture-backend-template scripts/new-feature.sh,
|
|
* `__Feature__Controller.java.tmpl`): `POST /<plural>` answers 201 with the
|
|
* new item in the Envelope, `GET /<plural>/{id}` reads one. With them come a
|
|
* detail page, a create form with the unknown-result handling, and tests that
|
|
* answer with the backend's own bodies. The base templates in
|
|
* `create-feature.ts` call into this file where the slice adds to one of
|
|
* their files; the files only the slice has are rendered here whole.
|
|
*
|
|
* The backend generates a NOT_IDEMPOTENT create, which reads no
|
|
* Idempotency-Key, so the default command is NEVER: no key, no resend.
|
|
* `--keyed` is for a backend create made KEYED with its IdempotencyExecutor
|
|
* (its docs/manual/05-idempotency.md). Like the rest of the command, nothing
|
|
* here imports a sample feature.
|
|
*
|
|
* 1105/16-02. The backend scaffold facts copied here (name limit, error
|
|
* codes, 201 and the endpoints, the check order behind refusedBeforeWrite)
|
|
* and the path rule in create-feature.ts are listed with their backend
|
|
* files in config/contracts/backend-contract-pin.json `scaffoldSources`;
|
|
* `check:backend-contract-drift` says when one of those files changes.
|
|
*/
|
|
|
|
export type WriteSemantics = "NEVER" | "KEYED";
|
|
|
|
export type SliceRoute = Readonly<{
|
|
routeId: string;
|
|
path: string;
|
|
chunkId: string;
|
|
moduleId: string;
|
|
loadingSurface: string;
|
|
}>;
|
|
|
|
export type WriteSlice = Readonly<{
|
|
semantics: WriteSemantics;
|
|
/** The detail route's path parameter. */
|
|
idParam: string;
|
|
detail: SliceRoute;
|
|
create: SliceRoute;
|
|
getOperationId: string;
|
|
createOperationId: string;
|
|
/** The backend scaffold's `__FEATURE___INVALID` (400) and `_NOT_FOUND` (404). */
|
|
invalidCode: string;
|
|
notFoundCode: string;
|
|
}>;
|
|
|
|
type SliceNames = Readonly<{
|
|
id: string;
|
|
base: string;
|
|
upper: string;
|
|
pascal: string;
|
|
camel: string;
|
|
title: string;
|
|
}>;
|
|
|
|
type SliceShape = Readonly<{
|
|
names: SliceNames;
|
|
routeId: string;
|
|
apiPath: string;
|
|
write: WriteSlice;
|
|
}>;
|
|
|
|
/** The backend aggregate's `NAME_MAX_LENGTH`; its create refuses a longer name. */
|
|
const BACKEND_NAME_MAX_LENGTH = 100;
|
|
|
|
export function planWriteSlice(
|
|
names: SliceNames,
|
|
listPath: string,
|
|
semantics: WriteSemantics,
|
|
): WriteSlice {
|
|
const { base, camel, upper } = names;
|
|
const route = (suffix: string, path: string): SliceRoute =>
|
|
Object.freeze({
|
|
routeId: `${upper}_${suffix.toUpperCase()}`,
|
|
path,
|
|
chunkId: `route-${base}-${suffix}`,
|
|
moduleId: `${base}-${suffix}-page`,
|
|
loadingSurface: `${base}-${suffix}`,
|
|
});
|
|
return Object.freeze({
|
|
semantics,
|
|
idParam: `${camel}Id`,
|
|
// `items/` keeps the detail apart from the static `new` (01 6단계).
|
|
detail: route("detail", `${listPath}/items/:${camel}Id`),
|
|
create: route("create", `${listPath}/new`),
|
|
getOperationId: `${upper}_GET_ITEM`,
|
|
createOperationId: `${upper}_CREATE_ITEM`,
|
|
invalidCode: `${upper}_INVALID`,
|
|
notFoundCode: `${upper}_NOT_FOUND`,
|
|
});
|
|
}
|
|
|
|
export function writeSliceMessageKeys(names: SliceNames, slice: WriteSlice): string[] {
|
|
const { camel } = names;
|
|
return [
|
|
...[slice.detail.routeId, slice.create.routeId].flatMap((routeId) => [
|
|
`route.${routeId}.navigation`,
|
|
`route.${routeId}.title`,
|
|
]),
|
|
`${camel}.list.create`,
|
|
`${camel}.detail.titlePending`,
|
|
`${camel}.detail.itemId`,
|
|
`${camel}.form.title`,
|
|
`${camel}.form.name`,
|
|
`${camel}.form.save`,
|
|
`${camel}.form.saving`,
|
|
];
|
|
}
|
|
|
|
/** Route titles, ko-KR then en-US. The contract's `title` repeats ko-KR. */
|
|
export function writeSliceRouteTitles(names: SliceNames) {
|
|
const { title } = names;
|
|
return Object.freeze({
|
|
detail: Object.freeze({ ko: `${title} 상세`, en: `${title} detail` }),
|
|
create: Object.freeze({ ko: `${title} 만들기`, en: `New ${title}` }),
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Fragments the base templates insert.
|
|
|
|
export function renderWriteRoutes({ names, write }: SliceShape): string {
|
|
const titles = writeSliceRouteTitles(names);
|
|
const entry = (route: SliceRoute, paramsSchema: string, title: string) => ` ${route.routeId}: Object.freeze({
|
|
routeId: "${route.routeId}",
|
|
path: "${route.path}",
|
|
paramsSchema: ${paramsSchema},
|
|
searchSchema: null,
|
|
access: "session-required",
|
|
loadingSurface: "${route.loadingSurface}",
|
|
errorSurface: "feature-boundary",
|
|
chunkId: "${route.chunkId}",
|
|
title: "${title}",
|
|
navigationLabel: null,
|
|
navigationOrder: null,
|
|
}),
|
|
`;
|
|
return (
|
|
entry(write.detail, `"${names.pascal}Params"`, titles.detail.ko) +
|
|
entry(write.create, "null", titles.create.ko)
|
|
);
|
|
}
|
|
|
|
export function renderWriteRouteRuntimeContracts({ names, write }: SliceShape): string {
|
|
const entry = (route: SliceRoute, paramsCodec: string) => ` ${route.routeId}: Object.freeze({
|
|
routeId: "${route.routeId}",
|
|
moduleId: "${route.moduleId}",
|
|
paramsCodec: "${paramsCodec}",
|
|
searchCodec: "none",
|
|
}),
|
|
`;
|
|
return entry(write.detail, `${names.pascal}Params`) + entry(write.create, "none");
|
|
}
|
|
|
|
export function renderWriteSchemas({ names, write }: SliceShape): string {
|
|
const { camel, pascal, upper } = names;
|
|
return `
|
|
/** The backend aggregate's \`NAME_MAX_LENGTH\`. The request and the form share it. */
|
|
export const ${upper}_NAME_MAX_LENGTH = ${BACKEND_NAME_MAX_LENGTH};
|
|
|
|
/**
|
|
* The detail route's params and the GET's input. The backend reads the id as
|
|
* a canonical UUID and answers another text with 400 BAD_PARAMETER.
|
|
*/
|
|
export const ${camel}ParamsSchema = z
|
|
.object({
|
|
${write.idParam}: z.string().trim().min(1).max(120),
|
|
})
|
|
.strict();
|
|
|
|
export type ${pascal}Params = z.output<typeof ${camel}ParamsSchema>;
|
|
|
|
/**
|
|
* The backend's \`Create__Feature__HttpRequest\`. It has no bean validation:
|
|
* the aggregate refuses a blank or longer name with 400 ${write.invalidCode}.
|
|
*/
|
|
export const ${camel}CreateCommandSchema = z
|
|
.object({
|
|
name: z.string().min(1).max(${upper}_NAME_MAX_LENGTH),
|
|
})
|
|
.strict();
|
|
|
|
export type ${pascal}CreateRequest = z.output<typeof ${camel}CreateCommandSchema>;
|
|
`;
|
|
}
|
|
|
|
export function renderWriteValidators({ names }: SliceShape): string {
|
|
const { camel, pascal } = names;
|
|
return ` ${pascal}Params: zodValidator("${pascal}Params", ${camel}ParamsSchema),
|
|
${pascal}ItemPayload: zodValidator("${pascal}ItemPayload", ${camel}ItemDtoSchema),
|
|
${pascal}CreateCommand: zodValidator("${pascal}CreateCommand", ${camel}CreateCommandSchema),
|
|
`;
|
|
}
|
|
|
|
export function renderWriteMapper({ names }: SliceShape): string {
|
|
const { pascal } = names;
|
|
return `
|
|
export function map${pascal}Item(
|
|
dto: ${pascal}ItemDto,
|
|
): BoundaryMappingResult<${pascal}ItemView> {
|
|
return mappingSuccess(toView(dto));
|
|
}
|
|
`;
|
|
}
|
|
|
|
export function renderWriteSchemaRows({ names }: SliceShape): string {
|
|
const { pascal } = names;
|
|
const row = (
|
|
schemaId: string,
|
|
boundary: string,
|
|
direction: string,
|
|
unknownFieldPolicy: string,
|
|
) => ` ${schemaId}: Object.freeze({
|
|
schemaId: "${schemaId}",
|
|
boundary: "${boundary}",
|
|
owner: OWNER,
|
|
runtime: "zod",
|
|
schemaVersion: 1,
|
|
direction: "${direction}",
|
|
unknownFieldPolicy: "${unknownFieldPolicy}",
|
|
}),
|
|
`;
|
|
return (
|
|
row(`${pascal}Params`, "route-params", "REQUEST", "REJECT_UNKNOWN") +
|
|
row(`${pascal}ItemPayload`, "api-response", "RESPONSE", "STRIP_UNKNOWN") +
|
|
row(`${pascal}CreateCommand`, "api-request", "REQUEST", "REJECT_UNKNOWN")
|
|
);
|
|
}
|
|
|
|
export function renderWriteDescriptors({ names, write }: SliceShape): string {
|
|
const { base, pascal, upper } = names;
|
|
const keyed = write.semantics === "KEYED";
|
|
const semantics = keyed
|
|
? ` // The backend create runs behind its IdempotencyExecutor
|
|
// (http-contract.md §2): the same key replays, never applies twice.
|
|
retrySemantics: "KEYED" as const,`
|
|
: ` // new-feature.sh generates a NOT_IDEMPOTENT create: the backend reads no
|
|
// Idempotency-Key and a second request creates a second item. Make the
|
|
// backend create KEYED (its docs/manual/05-idempotency.md) before this.
|
|
retrySemantics: "NEVER" as const,`;
|
|
const recovery = keyed
|
|
? ` // The intent's key, which the executor sends as Idempotency-Key. Recorded
|
|
// in FE-REG-API; the executor does not read it.
|
|
commandRecovery: Object.freeze({
|
|
mode: "IDEMPOTENCY_REPLAY" as const,
|
|
operationIdentityField: "idempotencyKey",
|
|
}),`
|
|
: ` commandRecovery: null,`;
|
|
const budget = keyed
|
|
? ` // One automatic resend, with the same key, after 503
|
|
// IDEMPOTENCY_UNAVAILABLE (refused before the work ran). The app's
|
|
// MAX_RETRY_ATTEMPTS caps it too. A lost response is never resent on its
|
|
// own: the form offers the same-key resend.
|
|
retryBudget: 1 as const,`
|
|
: ` retryBudget: 0 as const,`;
|
|
return `
|
|
/**
|
|
* The paired backend's \`GET /<plural>/{id}\`: the item in the Envelope, or
|
|
* 404 ${write.notFoundCode}.
|
|
*/
|
|
export const ${write.getOperationId}_CONTRACT = Object.freeze({
|
|
contract: Object.freeze({
|
|
operationId: "${write.getOperationId}",
|
|
method: "GET" as const,
|
|
pathTemplate: \`\${API_PATH}/{id}\`,
|
|
inputValidator: ${upper}_VALIDATORS.${pascal}Params,
|
|
outputValidator: ${upper}_VALIDATORS.${pascal}ItemPayload,
|
|
problemValidator: ${upper}_VALIDATORS.${pascal}Problem,
|
|
acceptedStatuses: Object.freeze([200]),
|
|
emptyBodyStatuses: Object.freeze([]),
|
|
retrySemantics: "SAFE" as const,
|
|
requestBody: "NONE" as const,
|
|
responseBody: "REQUIRED_JSON" as const,
|
|
responseEnvelope: "ENVELOPE_V1" as const,
|
|
commandRecovery: null,
|
|
commandEffect: null,
|
|
projectRequest(input: ${pascal}Params) {
|
|
return Object.freeze({
|
|
pathValues: Object.freeze({ id: input.${write.idParam} }),
|
|
queryEntries: Object.freeze([]),
|
|
body: null,
|
|
});
|
|
},
|
|
}),
|
|
frontend: Object.freeze({
|
|
policyId: "${upper}_GET_V1",
|
|
requestByteLimit: 0,
|
|
responseByteLimit: 32_768,
|
|
totalDeadlineMs: 10_000,
|
|
retryBudget: 2 as const,
|
|
authProfileId: "EXTERNAL_BEARER",
|
|
diagnosticsOperation: "${base}.detail",
|
|
}),
|
|
}) satisfies InstalledHttpContract<${pascal}Params, ${pascal}ItemDto, ${pascal}Problem>;
|
|
|
|
/**
|
|
* 1103/03-01. Whether a failed create applied. The executor's backend table
|
|
* decides 400, 409, 422 and the backend's own 5xx answers; \`classifyProblem\`
|
|
* gets every other status.
|
|
*/
|
|
const ${upper}_CREATE_EFFECT: CommandEffectDescriptor<${pascal}Problem> = Object.freeze({
|
|
successEffect: "APPLIED_CONFIRMED" as const,
|
|
classifyProblem: () => "MAYBE_APPLIED" as const,
|
|
// The backend refuses these before the use case runs: 401 in the security
|
|
// filter chain, 403 at the use case's @RequiresPermission proxy, 429 in the
|
|
// rate-limit interceptor. Recheck if the use case asks AuthorizationPort
|
|
// after it writes.
|
|
classifyStatus: () => "NOT_APPLIED" as const,
|
|
// Create<Feature>UseCase checks the name before its transaction. List a
|
|
// code here only when the endpoint raises it before any write.
|
|
refusedBeforeWrite: Object.freeze(["${write.invalidCode}"]),
|
|
});
|
|
|
|
/** The paired backend's \`POST /<plural>\`: 201 with the new item in the Envelope. */
|
|
export const ${write.createOperationId}_CONTRACT = Object.freeze({
|
|
contract: Object.freeze({
|
|
operationId: "${write.createOperationId}",
|
|
method: "POST" as const,
|
|
pathTemplate: API_PATH,
|
|
inputValidator: ${upper}_VALIDATORS.${pascal}CreateCommand,
|
|
outputValidator: ${upper}_VALIDATORS.${pascal}ItemPayload,
|
|
problemValidator: ${upper}_VALIDATORS.${pascal}Problem,
|
|
acceptedStatuses: Object.freeze([201]),
|
|
emptyBodyStatuses: Object.freeze([]),
|
|
${semantics}
|
|
requestBody: "JSON" as const,
|
|
responseBody: "REQUIRED_JSON" as const,
|
|
responseEnvelope: "ENVELOPE_V1" as const,
|
|
${recovery}
|
|
commandEffect: ${upper}_CREATE_EFFECT,
|
|
projectRequest(input: ${pascal}CreateRequest) {
|
|
return Object.freeze({
|
|
pathValues: Object.freeze({}),
|
|
queryEntries: Object.freeze([]),
|
|
body: Object.freeze({ name: input.name }),
|
|
});
|
|
},
|
|
}),
|
|
frontend: Object.freeze({
|
|
policyId: "${upper}_CREATE_V1",
|
|
requestByteLimit: 4_096,
|
|
responseByteLimit: 32_768,
|
|
totalDeadlineMs: 10_000,
|
|
${budget}
|
|
authProfileId: "EXTERNAL_BEARER",
|
|
diagnosticsOperation: "${base}.create",
|
|
}),
|
|
}) satisfies InstalledHttpContract<${pascal}CreateRequest, ${pascal}ItemDto, ${pascal}Problem>;
|
|
`;
|
|
}
|
|
|
|
export function renderWriteMessages({ names, write }: SliceShape, locale: "ko" | "en"): string {
|
|
const { camel } = names;
|
|
const titles = writeSliceRouteTitles(names);
|
|
const copy =
|
|
locale === "ko"
|
|
? {
|
|
create: "새 항목 만들기",
|
|
titlePending: `${names.title} 항목`,
|
|
itemId: "ID",
|
|
formTitle: titles.create.ko,
|
|
name: "이름",
|
|
save: "저장",
|
|
saving: "저장 중…",
|
|
}
|
|
: {
|
|
create: "Create item",
|
|
titlePending: `${names.title} item`,
|
|
itemId: "ID",
|
|
formTitle: titles.create.en,
|
|
name: "Name",
|
|
save: "Save",
|
|
saving: "Saving…",
|
|
};
|
|
return ` "route.${write.detail.routeId}.navigation": "${titles.detail[locale]}",
|
|
"route.${write.detail.routeId}.title": "${titles.detail[locale]}",
|
|
"route.${write.create.routeId}.navigation": "${titles.create[locale]}",
|
|
"route.${write.create.routeId}.title": "${titles.create[locale]}",
|
|
"${camel}.list.create": "${copy.create}",
|
|
"${camel}.detail.titlePending": "${copy.titlePending}",
|
|
"${camel}.detail.itemId": "${copy.itemId}",
|
|
"${camel}.form.title": "${copy.formTitle}",
|
|
"${camel}.form.name": "${copy.name}",
|
|
"${camel}.form.save": "${copy.save}",
|
|
"${camel}.form.saving": "${copy.saving}",
|
|
`;
|
|
}
|
|
|
|
export function renderWriteGatewayOperations({ names, write }: SliceShape): string {
|
|
const { pascal } = names;
|
|
return ` ${write.getOperationId}: define${pascal}HttpOperation({
|
|
contract: ${write.getOperationId}_CONTRACT,
|
|
routeId: "${write.detail.routeId}",
|
|
mapSuccess: map${pascal}Item,
|
|
}),
|
|
${write.createOperationId}: define${pascal}HttpOperation({
|
|
contract: ${write.createOperationId}_CONTRACT,
|
|
routeId: "${write.create.routeId}",
|
|
mapSuccess: map${pascal}Item,
|
|
// The scaffold aggregate has one rule, on the name: show the backend's
|
|
// refusal on that field. Map each field the aggregate grows.
|
|
mapProblem: (problem) =>
|
|
problem.code === "${write.invalidCode}"
|
|
? Object.freeze({
|
|
kind: "VALIDATION_REJECTED" as const,
|
|
code: problem.code,
|
|
validationIssues: Object.freeze([Object.freeze({ path: "name", code: "INVALID" })]),
|
|
})
|
|
: undefined,
|
|
}),
|
|
`;
|
|
}
|
|
|
|
export function renderWriteGatewayMethods({ write }: SliceShape): string {
|
|
return ` get(${write.idParam}, context) {
|
|
return http.execute("${write.getOperationId}", Object.freeze({ ${write.idParam} }), context);
|
|
},
|
|
create(command, context) {
|
|
return http.execute("${write.createOperationId}", command, context);
|
|
},
|
|
`;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Files only the slice has.
|
|
|
|
export function renderRouteCodecs({ names }: SliceShape): string {
|
|
const { base, camel, pascal, upper } = names;
|
|
return `import { ${camel}ParamsSchema } from "../contracts/${base}-schemas.ts";
|
|
|
|
/**
|
|
* The route codecs, keyed by the codec ids \`routeRuntimeContracts\` names.
|
|
* They load with the context routes (\`context-routes.ts\` puts them on each
|
|
* handle), not with the declaration in the initial chunk.
|
|
*/
|
|
export const ${upper}_ROUTE_CODECS = {
|
|
${pascal}Params: ${camel}ParamsSchema,
|
|
} as const;
|
|
`;
|
|
}
|
|
|
|
export function renderUseItem({ names }: SliceShape): string {
|
|
const { base, pascal, upper } = names;
|
|
return `import { bindQuery, type QueryResultMeasure } from "../../../contracts/server-state.ts";
|
|
import { useApplicationQuery } from "../../../presentation/adapters/query/application-query.ts";
|
|
import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx";
|
|
import { useApplicationFeature } from "../../../presentation/providers/application-provider.tsx";
|
|
import {
|
|
${upper}_FEATURE_ID,
|
|
${upper}_ITEM_QUERY_NAMESPACE,
|
|
} from "../contracts/${base}-feature-contract.ts";
|
|
import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts";
|
|
|
|
const UTF8 = new TextEncoder();
|
|
|
|
function measureItem(item: ${pascal}ItemView): QueryResultMeasure {
|
|
return {
|
|
itemCount: 1,
|
|
estimatedBytes: UTF8.encode(item.itemId).byteLength + UTF8.encode(item.name).byteLength + 16,
|
|
};
|
|
}
|
|
|
|
/** One item. A save of this feature invalidates its namespace, so a new item shows. */
|
|
export function use${pascal}Item(itemId: string) {
|
|
const input = useApplicationFeature(${upper}_FEATURE_ID);
|
|
const scope = useServerStateScope();
|
|
return useApplicationQuery(
|
|
bindQuery(
|
|
{
|
|
definitionId: "${base}-item-detail-v1",
|
|
definitionVersion: 1,
|
|
namespace: ${upper}_ITEM_QUERY_NAMESPACE,
|
|
profileId: "DETAIL_STANDARD",
|
|
measureResult: measureItem,
|
|
execute: (selected: string, { signal }) => input.getItem(selected, { signal }),
|
|
},
|
|
itemId,
|
|
scope,
|
|
),
|
|
);
|
|
}
|
|
`;
|
|
}
|
|
|
|
export function renderUseCreate({ names, write }: SliceShape): string {
|
|
const { base, pascal, upper } = names;
|
|
return `import {
|
|
commandMutationIdentity,
|
|
type BoundMutation,
|
|
} from "../../../contracts/server-state.ts";
|
|
import { useApplicationMutation } from "../../../presentation/adapters/query/application-query.ts";
|
|
import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx";
|
|
import { useApplicationFeature } from "../../../presentation/providers/application-provider.tsx";
|
|
import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts";
|
|
import { ${write.createOperationId}_CONTRACT } from "../contracts/${base}-contract-contribution.ts";
|
|
import {
|
|
${upper}_FEATURE_ID,
|
|
${upper}_ITEM_INVALIDATION_TOPIC,
|
|
} from "../contracts/${base}-feature-contract.ts";
|
|
import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts";
|
|
|
|
/**
|
|
* 1103/16-05. The operation id and whether the intent carries an
|
|
* idempotency key are the descriptor's. A second save while one runs is
|
|
* refused, and a saved item invalidates the list and the detail.
|
|
*/
|
|
const ${upper}_CREATE_MUTATION_POLICY = Object.freeze({
|
|
definitionId: "${base}-create-v1",
|
|
definitionVersion: 1,
|
|
...commandMutationIdentity(${write.createOperationId}_CONTRACT),
|
|
duplicatePolicy: "REJECT_WHILE_ACTIVE" as const,
|
|
invalidate: Object.freeze([${upper}_ITEM_INVALIDATION_TOPIC]),
|
|
});
|
|
|
|
export function use${pascal}Create() {
|
|
const input = useApplicationFeature(${upper}_FEATURE_ID);
|
|
const scope = useServerStateScope();
|
|
const mutation: BoundMutation<${pascal}CreateCommand, ${pascal}ItemView> = Object.freeze({
|
|
...${upper}_CREATE_MUTATION_POLICY,
|
|
scope,
|
|
execute: input.createItem,
|
|
});
|
|
return useApplicationMutation(mutation);
|
|
}
|
|
`;
|
|
}
|
|
|
|
export function renderForm({ names }: SliceShape): string {
|
|
const { base, camel, pascal, upper } = names;
|
|
return `import { z } from "../../../contracts/zod.ts";
|
|
import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts";
|
|
import { ${upper}_NAME_MAX_LENGTH } from "../contracts/${base}-schemas.ts";
|
|
|
|
/** What the user types. The length comes from the request schema's constant. */
|
|
export const ${camel}FormSchema = z
|
|
.object({
|
|
name: z.string().trim().min(1).max(${upper}_NAME_MAX_LENGTH),
|
|
})
|
|
.strict();
|
|
|
|
export type ${pascal}FormValues = z.infer<typeof ${camel}FormSchema>;
|
|
|
|
export const ${upper}_FORM_DEFAULTS: ${pascal}FormValues = Object.freeze({ name: "" });
|
|
|
|
export function to${pascal}CreateCommand(values: ${pascal}FormValues): ${pascal}CreateCommand {
|
|
return Object.freeze({ name: values.name });
|
|
}
|
|
`;
|
|
}
|
|
|
|
export function renderDetailPage({ names, routeId }: SliceShape): string {
|
|
const { base, camel, pascal } = names;
|
|
return `import { Link } from "react-router-dom";
|
|
|
|
import {
|
|
AsyncSurface,
|
|
DetailPage,
|
|
} from "../../../presentation/design-system/index.ts";
|
|
import { useLocale } from "../../../presentation/i18n/index.ts";
|
|
import { ${camel}RouteUrl, use${pascal}ItemId } from "./${base}-routes.ts";
|
|
import { use${pascal}Item } from "./use-${base}-item.ts";
|
|
|
|
/** The heading stays while the item loads or fails, so the page always has an h1. */
|
|
export default function ${pascal}DetailPage() {
|
|
const { message } = useLocale();
|
|
const itemId = use${pascal}ItemId();
|
|
const query = use${pascal}Item(itemId);
|
|
const item = query.data;
|
|
return (
|
|
<DetailPage
|
|
key={itemId}
|
|
breadcrumb={<Link to={${camel}RouteUrl("${routeId}")}>{message("${camel}.list.title")}</Link>}
|
|
heading={{ title: item?.name ?? message("${camel}.detail.titlePending") }}
|
|
metadata={
|
|
item ? (
|
|
<dl>
|
|
<dt>{message("${camel}.detail.itemId")}</dt>
|
|
<dd>{item.itemId}</dd>
|
|
</dl>
|
|
) : null
|
|
}
|
|
feedback={<AsyncSurface state={query.state} onRetry={query.retry} />}
|
|
/>
|
|
);
|
|
}
|
|
`;
|
|
}
|
|
|
|
export function renderCreatePage({ names, routeId, write }: SliceShape): string {
|
|
const { base, camel, pascal, upper } = names;
|
|
return `import { Link, useNavigate } from "react-router-dom";
|
|
|
|
import {
|
|
Button,
|
|
DirtyNavigationDialog,
|
|
ErrorSummary,
|
|
Form,
|
|
FormActions,
|
|
FormField,
|
|
FormPage,
|
|
FormSaveFeedback,
|
|
useAppForm,
|
|
useDirtyNavigationGuard,
|
|
} from "../../../presentation/design-system/index.ts";
|
|
import { useLocale } from "../../../presentation/i18n/index.ts";
|
|
import {
|
|
${upper}_FORM_DEFAULTS,
|
|
${camel}FormSchema,
|
|
to${pascal}CreateCommand,
|
|
type ${pascal}FormValues,
|
|
} from "./${base}-form.ts";
|
|
import { ${camel}RouteUrl } from "./${base}-routes.ts";
|
|
import { use${pascal}Create } from "./use-${base}-create.ts";
|
|
|
|
/**
|
|
* The create form. A saved item opens its detail page, unless the user left
|
|
* this page while it saved. The backend's refusal
|
|
* of the name (400 ${write.invalidCode}, refused before the write) shows on
|
|
* the field and the form saves again. A save whose result is unknown (the
|
|
* response was lost) keeps the form: the user checks, or, for a KEYED
|
|
* command, resends the same request with the same key. Confirming it was
|
|
* applied opens the list, which shows whether the item is there.
|
|
*/
|
|
export default function ${pascal}CreatePage() {
|
|
const navigate = useNavigate();
|
|
const { message } = useLocale();
|
|
const fieldLabels = {
|
|
name: message("${camel}.form.name"),
|
|
} satisfies Record<keyof ${pascal}FormValues, string>;
|
|
const mutation = use${pascal}Create();
|
|
// The form holds the rules of a save through the mutation: no new save
|
|
// while one is unknown or another runs, confirm and resend of an unknown
|
|
// one, and what the page does after a save only while it is still open
|
|
// (useAppForm \`mutation\` and \`onSaved\`, FormSaveFeedback).
|
|
const form = useAppForm({
|
|
schema: ${camel}FormSchema,
|
|
defaultValues: ${upper}_FORM_DEFAULTS,
|
|
allowedServerFields: ["name"],
|
|
mapToCommand: to${pascal}CreateCommand,
|
|
submit: mutation.submit,
|
|
mutation,
|
|
onSaved: (item) => {
|
|
void navigate(
|
|
${camel}RouteUrl("${write.detail.routeId}", {
|
|
params: { ${write.idParam}: item.itemId },
|
|
}),
|
|
);
|
|
},
|
|
});
|
|
const guard = useDirtyNavigationGuard(form.dirty && !form.pending);
|
|
|
|
return (
|
|
<Form id={form.formId} pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
|
|
<FormPage
|
|
feedbackId={form.feedbackId}
|
|
breadcrumb={<Link to={${camel}RouteUrl("${routeId}")}>{message("${camel}.list.title")}</Link>}
|
|
heading={{ title: message("${camel}.form.title") }}
|
|
errorSummary={
|
|
<ErrorSummary
|
|
fieldErrors={form.fieldErrors}
|
|
formErrors={form.formErrors}
|
|
fieldLabels={fieldLabels}
|
|
fieldId={form.fieldId}
|
|
onFocusField={form.focusField}
|
|
/>
|
|
}
|
|
fields={
|
|
<FormField {...form.field("name")} label={fieldLabels.name} autoComplete="off" required />
|
|
}
|
|
formActions={
|
|
<FormActions sticky>
|
|
{/* Busy, not disabled, while saving: a disabled button drops
|
|
keyboard focus (1103/08-02). */}
|
|
<Button
|
|
type="submit"
|
|
pending={form.pending}
|
|
pendingLabel={message("${camel}.form.saving")}
|
|
disabled={form.effectUnknown || form.otherSaveRunning}
|
|
>
|
|
{message("${camel}.form.save")}
|
|
</Button>
|
|
</FormActions>
|
|
}
|
|
feedback={
|
|
<FormSaveFeedback
|
|
form={form}
|
|
// The list shows whether the item is there; the form alone
|
|
// would show nothing but an emptied input (1105/08-02).
|
|
onConfirmed={() => {
|
|
void navigate(${camel}RouteUrl("${routeId}"));
|
|
}}
|
|
/>
|
|
}
|
|
guard={<DirtyNavigationDialog guard={guard} />}
|
|
/>
|
|
</Form>
|
|
);
|
|
}
|
|
`;
|
|
}
|
|
|
|
export function renderCreatePageTest({ names, apiPath, write }: SliceShape): string {
|
|
const { base, camel, upper } = names;
|
|
const keyed = write.semantics === "KEYED";
|
|
const unknownTest = keyed
|
|
? ` // KEYED: the key is kept, and the resend carries it, so the backend's
|
|
// IdempotencyExecutor replays the first request instead of applying twice.
|
|
it("resends a create whose response was lost with the same key", async () => {
|
|
const posts = answerCreate(() => HttpResponse.error());
|
|
const user = await openForm();
|
|
await user.type(await nameField(), "First item");
|
|
await user.click(saveButton());
|
|
expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible();
|
|
expect(saveButton()).toBeDisabled();
|
|
|
|
answerCreate(() => created(), posts);
|
|
answerItem();
|
|
await user.click(screen.getByRole("button", { name: KO_MESSAGES["action.resendMutation"] }));
|
|
|
|
expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible();
|
|
expect(posts).toHaveLength(2);
|
|
expect(posts[0]!.headers.get("idempotency-key")).toMatch(/^[\\x21-\\x7e]+$/u);
|
|
expect(posts[1]!.headers.get("idempotency-key")).toBe(posts[0]!.headers.get("idempotency-key"));
|
|
});`
|
|
: ` // NEVER: the backend scaffold's create reads no key, so a resend would be a
|
|
// second, unprotected create. The form keeps the unknown result and offers
|
|
// no resend; the user checks the list.
|
|
it("keeps a create whose response was lost unknown and offers no resend", async () => {
|
|
const posts = answerCreate(() => HttpResponse.error());
|
|
const user = await openForm();
|
|
await user.type(await nameField(), "First item");
|
|
await user.click(saveButton());
|
|
|
|
expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible();
|
|
expect(
|
|
screen.queryByRole("button", { name: KO_MESSAGES["action.resendMutation"] }),
|
|
).toBeNull();
|
|
expect(saveButton()).toBeDisabled();
|
|
expect(posts).toHaveLength(1);
|
|
expect(posts[0]!.headers.get("idempotency-key")).toBeNull();
|
|
});`;
|
|
return `// @vitest-environment jsdom
|
|
|
|
import { screen, waitFor, within } from "@testing-library/react";
|
|
import { http, HttpResponse, type JsonBodyType } from "msw";
|
|
import { setupServer } from "msw/node";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
|
|
|
import { ${upper}_MESSAGE_CATALOGS } from "../../../src/features/${names.id}/contracts/${base}-message-catalog.ts";
|
|
import { ${camel}RouteUrl } from "../../../src/features/${names.id}/presentation/${base}-routes.ts";
|
|
import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts";
|
|
import { API, openSignedIn } from "./${base}-test-app.tsx";
|
|
|
|
const MESSAGES = ${upper}_MESSAGE_CATALOGS["ko-KR"];
|
|
const ITEM_ID = "0b6f2c1e-5d4a-4f3b-9c2d-1a2b3c4d5e6f";
|
|
const META = { requestId: "req-1", traceId: "0af7651916cd43dd8448eb211c80319c" };
|
|
|
|
const api = setupServer();
|
|
beforeAll(() => api.listen({ onUnhandledRequest: "error" }));
|
|
afterEach(() => api.resetHandlers());
|
|
afterAll(() => api.close());
|
|
|
|
/**
|
|
* The paired backend's answers, written out (new-feature.sh's controller and
|
|
* http-contract.md §1), not taken from the shared scenarios: a descriptor
|
|
* that stops reading this wire fails here.
|
|
*/
|
|
function created() {
|
|
return HttpResponse.json(
|
|
{ success: true, data: { id: ITEM_ID, name: "First item" }, meta: META },
|
|
{ status: 201, headers: { Location: \`\${API}${apiPath}/\${ITEM_ID}\` } },
|
|
);
|
|
}
|
|
|
|
function refusedName() {
|
|
return HttpResponse.json(
|
|
{
|
|
success: false,
|
|
error: {
|
|
code: "${write.invalidCode}",
|
|
category: "VALIDATION",
|
|
message: "backend message",
|
|
retryable: false,
|
|
},
|
|
meta: META,
|
|
},
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
|
|
/** Answers POST ${apiPath} and keeps a copy of each request it receives. */
|
|
function answerCreate(respond: () => Response, posts: Request[] = []) {
|
|
api.use(
|
|
http.post(\`\${API}${apiPath}\`, ({ request }) => {
|
|
posts.push(request.clone());
|
|
return respond();
|
|
}),
|
|
);
|
|
return posts;
|
|
}
|
|
|
|
function answerItem(body: JsonBodyType = { id: ITEM_ID, name: "First item" }) {
|
|
api.use(
|
|
http.get(\`\${API}${apiPath}/:id\`, () =>
|
|
HttpResponse.json({ success: true, data: body, meta: META }),
|
|
),
|
|
);
|
|
}
|
|
|
|
function answerList() {
|
|
api.use(
|
|
http.get(\`\${API}${apiPath}\`, () =>
|
|
HttpResponse.json({ success: true, data: [{ id: ITEM_ID, name: "First item" }], meta: META }),
|
|
),
|
|
);
|
|
}
|
|
|
|
async function openForm() {
|
|
const user = await openSignedIn(${camel}RouteUrl("${write.create.routeId}"));
|
|
expect(
|
|
await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.form.title"] }),
|
|
).toBeVisible();
|
|
return user;
|
|
}
|
|
|
|
// The label also holds the required mark, so the name is matched, not equal.
|
|
const nameField = () =>
|
|
screen.findByRole("textbox", { name: new RegExp(MESSAGES["${camel}.form.name"], "u") });
|
|
const saveButton = () => screen.getByRole("button", { name: MESSAGES["${camel}.form.save"] });
|
|
|
|
describe("${names.id} create form on the paired backend", () => {
|
|
it("saves a new item and opens it", async () => {
|
|
const posts = answerCreate(created);
|
|
answerItem();
|
|
const user = await openForm();
|
|
await user.type(await nameField(), " First item ");
|
|
await user.click(saveButton());
|
|
|
|
expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible();
|
|
expect(await posts[0]!.json()).toEqual({ name: "First item" });
|
|
});
|
|
|
|
// 1103/03-01. refusedBeforeWrite makes this NOT_APPLIED, so the form takes
|
|
// the next save instead of holding an unknown result.
|
|
it("shows the backend's refusal of the name on the field and saves again", async () => {
|
|
const posts = answerCreate(refusedName);
|
|
const user = await openForm();
|
|
await user.type(await nameField(), "Refused name");
|
|
await user.click(saveButton());
|
|
|
|
expect(await screen.findAllByText(KO_MESSAGES["form.validation.invalid"])).not.toHaveLength(0);
|
|
expect(await nameField()).toHaveAttribute("aria-invalid", "true");
|
|
expect(saveButton()).toBeEnabled();
|
|
|
|
answerCreate(created, posts);
|
|
answerItem();
|
|
await user.clear(await nameField());
|
|
await user.type(await nameField(), "First item");
|
|
await user.click(saveButton());
|
|
|
|
expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible();
|
|
expect(posts).toHaveLength(2);
|
|
});
|
|
|
|
${unknownTest}
|
|
|
|
// 1105/08-02. Confirming an unknown create opens the list, which shows
|
|
// whether the item was saved; the form alone showed nothing.
|
|
it("opens the list after the user confirms a create whose response was lost", async () => {
|
|
const posts = answerCreate(() => HttpResponse.error());
|
|
answerList();
|
|
const user = await openForm();
|
|
await user.type(await nameField(), "First item");
|
|
await user.click(saveButton());
|
|
expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible();
|
|
|
|
await user.click(
|
|
screen.getByRole("button", { name: KO_MESSAGES["action.confirmMutationApplied"] }),
|
|
);
|
|
|
|
expect(
|
|
await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }),
|
|
).toBeVisible();
|
|
expect(await screen.findByText("First item")).toBeVisible();
|
|
expect(posts).toHaveLength(1);
|
|
});
|
|
|
|
// 1106/08-02. The user leaves for the list while the save runs. The save
|
|
// that ends then does not take them to the item: they stay on the list.
|
|
it("stays on the list the user went to while the create was saving", async () => {
|
|
let answerPost: ((response: Response) => void) | undefined;
|
|
api.use(
|
|
http.post(
|
|
\`\${API}${apiPath}\`,
|
|
() =>
|
|
new Promise<Response>((resolve) => {
|
|
answerPost = resolve;
|
|
}),
|
|
),
|
|
);
|
|
let lists = 0;
|
|
api.use(
|
|
http.get(\`\${API}${apiPath}\`, () => {
|
|
lists += 1;
|
|
return HttpResponse.json({
|
|
success: true,
|
|
data: lists === 1 ? [] : [{ id: ITEM_ID, name: "First item" }],
|
|
meta: META,
|
|
});
|
|
}),
|
|
);
|
|
answerItem();
|
|
const user = await openForm();
|
|
await user.type(await nameField(), "First item");
|
|
await user.click(saveButton());
|
|
await waitFor(() => expect(answerPost).toBeDefined());
|
|
|
|
await user.click(
|
|
within(screen.getByRole("navigation", { name: KO_MESSAGES["template.breadcrumb"] })).getByRole(
|
|
"link",
|
|
{ name: MESSAGES["${camel}.list.title"] },
|
|
),
|
|
);
|
|
expect(
|
|
await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }),
|
|
).toBeVisible();
|
|
answerPost?.(created());
|
|
|
|
// The create invalidates the list: the item there means the save ended.
|
|
// Opening the item would show its name as the heading within a second
|
|
// (earlier tests here loaded the detail page); it never comes.
|
|
expect(await screen.findByRole("link", { name: "First item" })).toBeVisible();
|
|
await expect(
|
|
screen.findByRole("heading", { level: 1, name: "First item" }, { timeout: 1_000 }),
|
|
).rejects.toThrow();
|
|
expect(
|
|
screen.getByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }),
|
|
).toBeVisible();
|
|
});
|
|
});
|
|
`;
|
|
}
|
|
|
|
/** The gateway test cases of the slice, inside the base gateway test's describe. */
|
|
export function renderWriteGatewayTests({ names, apiPath, write }: SliceShape): string {
|
|
const keyed = write.semantics === "KEYED";
|
|
const keyCases = keyed
|
|
? `
|
|
// http-contract.md §2: refused before the work ran, to be resent with the
|
|
// same key. The only answer the executor resends on its own (retryBudget 1).
|
|
it("sends the intent's key, and resends once with it after 503 IDEMPOTENCY_UNAVAILABLE", async () => {
|
|
const keys = answerCreate(201, CREATED_BODY);
|
|
// Registered last, so it answers first, once.
|
|
answerCreate(503, failure("IDEMPOTENCY_UNAVAILABLE", undefined, "TRANSIENT_DEPENDENCY"), keys, true);
|
|
|
|
await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toEqual({
|
|
ok: true,
|
|
value: { itemId: ITEM_ID, name: "First item" },
|
|
});
|
|
expect(keys).toEqual(["key-1", "key-1"]);
|
|
});
|
|
|
|
// http-contract.md §2: the first request with this key still runs. The
|
|
// result is unknown; the form resends it later with the same key, the
|
|
// executor never does on its own.
|
|
it("leaves 409 IDEMPOTENT_IN_FLIGHT maybe applied and does not resend it", async () => {
|
|
const keys = answerCreate(409, failure("IDEMPOTENT_IN_FLIGHT", undefined, "CONFLICT"));
|
|
|
|
await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { code: "IDEMPOTENT_IN_FLIGHT", effect: "MAYBE_APPLIED" },
|
|
});
|
|
expect(keys).toEqual(["key-1"]);
|
|
});
|
|
|
|
it("refuses a create without the intent's key before sending", async () => {
|
|
const keys = answerCreate(201, CREATED_BODY);
|
|
|
|
await expect(gateway().create({ name: "First item" }, {} as never)).resolves.toMatchObject({
|
|
ok: false,
|
|
});
|
|
expect(keys).toEqual([]);
|
|
});`
|
|
: `
|
|
it("sends no idempotency key: the backend scaffold's create reads none", async () => {
|
|
const keys = answerCreate(201, CREATED_BODY);
|
|
|
|
await gateway().create({ name: "First item" }, { intent: INTENT });
|
|
expect(keys).toEqual([null]);
|
|
});`;
|
|
return `
|
|
it("reads one item, and the backend's not-found code", async () => {
|
|
api.use(
|
|
http.get(\`\${API}${apiPath}/\${ITEM_ID}\`, () =>
|
|
HttpResponse.json({ success: true, data: { id: ITEM_ID, name: "First item" }, meta: META }),
|
|
),
|
|
);
|
|
await expect(gateway().get(ITEM_ID)).resolves.toEqual({
|
|
ok: true,
|
|
value: { itemId: ITEM_ID, name: "First item" },
|
|
});
|
|
|
|
api.use(
|
|
http.get(\`\${API}${apiPath}/\${ITEM_ID}\`, () =>
|
|
HttpResponse.json(failure("${write.notFoundCode}", undefined, "NOT_FOUND"), { status: 404 }),
|
|
),
|
|
);
|
|
await expect(gateway().get(ITEM_ID)).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "NOT_FOUND", code: "${write.notFoundCode}", httpStatus: 404 },
|
|
});
|
|
});
|
|
|
|
it("reads the 201 Envelope of a create", async () => {
|
|
answerCreate(201, CREATED_BODY);
|
|
|
|
await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toEqual({
|
|
ok: true,
|
|
value: { itemId: ITEM_ID, name: "First item" },
|
|
});
|
|
});
|
|
|
|
// 1103/03-01. Declared in refusedBeforeWrite: not applied, shown on the field.
|
|
it("reads 400 ${write.invalidCode} as not applied, on the name field", async () => {
|
|
answerCreate(400, failure("${write.invalidCode}"));
|
|
|
|
await expect(gateway().create({ name: "Refused" }, { intent: INTENT })).resolves.toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
kind: "VALIDATION_REJECTED",
|
|
code: "${write.invalidCode}",
|
|
effect: "NOT_APPLIED",
|
|
validationIssues: [{ path: "name", code: "INVALID" }],
|
|
},
|
|
});
|
|
});
|
|
|
|
it("leaves a create whose response was lost maybe applied, and does not resend it", async () => {
|
|
const keys: (string | null)[] = [];
|
|
api.use(
|
|
http.post(\`\${API}${apiPath}\`, ({ request }) => {
|
|
keys.push(request.headers.get("idempotency-key"));
|
|
return HttpResponse.error();
|
|
}),
|
|
);
|
|
|
|
await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { effect: "MAYBE_APPLIED" },
|
|
});
|
|
expect(keys).toHaveLength(1);
|
|
});
|
|
${keyCases}
|
|
`;
|
|
}
|
|
|
|
/** The slice's helpers for the gateway test, after its own. */
|
|
export function renderWriteGatewayHelpers({ apiPath, write }: SliceShape): string {
|
|
const key =
|
|
write.semantics === "KEYED"
|
|
? `
|
|
idempotencyKey: "key-1",`
|
|
: "";
|
|
return `
|
|
const ITEM_ID = "0b6f2c1e-5d4a-4f3b-9c2d-1a2b3c4d5e6f";
|
|
const CREATED_BODY = { success: true, data: { id: ITEM_ID, name: "First item" }, meta: META };
|
|
const INTENT = defineMutationIntent({
|
|
intentId: "intent-1",
|
|
operationId: "${write.createOperationId}",
|
|
canonicalInputIdentity: "create-1",${key}
|
|
createdAtMonotonicMs: 0,
|
|
});
|
|
|
|
/**
|
|
* Answers POST ${apiPath} and records the Idempotency-Key each request
|
|
* carried (\`null\` when none). The handler registered last answers first.
|
|
*/
|
|
function answerCreate(
|
|
status: number,
|
|
body: JsonBodyType,
|
|
keys: (string | null)[] = [],
|
|
once = false,
|
|
) {
|
|
api.use(
|
|
http.post(
|
|
\`\${API}${apiPath}\`,
|
|
({ request }) => {
|
|
keys.push(request.headers.get("idempotency-key"));
|
|
return HttpResponse.json(body, { status });
|
|
},
|
|
{ once },
|
|
),
|
|
);
|
|
return keys;
|
|
}
|
|
`;
|
|
}
|