feat(api): define public problem errors, pagination, and retry contract
This commit is contained in:
1 parent
b2f6e87bfe
commit
565ca94bbb
86 files changed
+8200
-154
No files matched your search
@@ -13,3 +13,4 @@ test-results/
|
||||
.env.*
|
||||
!.env.example
|
||||
*.log
|
||||
.orval-compat-*/
|
||||
@@ -5,3 +5,4 @@ src/shared/api/endpoints/
|
||||
src/shared/api/schemas/
|
||||
scripts/fixtures/
|
||||
pnpm-lock.yaml
|
||||
.orval-compat-*/
|
||||
+4
-1
@@ -1,5 +1,5 @@
|
||||
.DEFAULT_GOAL := help
|
||||
.PHONY: help install dev build generate fmt fmt-check lint lint-fix typecheck test check verify
|
||||
.PHONY: help install dev build generate check-orval-compat fmt fmt-check lint lint-fix typecheck test check verify
|
||||
|
||||
help: ## Show available frontend commands.
|
||||
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-12s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
|
||||
@@ -17,6 +17,9 @@ generate: ## Generate API client, query hooks, schemas, and MSW handlers.
|
||||
@if [ "$${API_PREPARED:-0}" != "1" ]; then $(MAKE) -C ../api bundle; fi
|
||||
pnpm run generate
|
||||
|
||||
check-orval-compat: ## Generate and type-check the OpenAPI 3.2 compatibility fixture in a temporary directory.
|
||||
pnpm run check:orval-compat
|
||||
|
||||
fmt: ## Format frontend source and configuration.
|
||||
pnpm run fmt
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ A React and TypeScript SPA built with Vite and organized using FSD. The current
|
||||
- `src/app/` starts the application; `pages/`, `widgets/`, `features/`, and `entities/` are the interface layers.
|
||||
- `src/shared/` contains shared components and the API client, including generated endpoints, Zod schemas, and MSW mocks.
|
||||
- `codegen/orval.config.ts` configures generation from the shared OpenAPI contract.
|
||||
- `scripts/` checks FSD boundaries.
|
||||
- `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture.
|
||||
|
||||
From the repository root, `make -C frontend dev` starts development and `make -C frontend check` runs checks and builds the app. In Docker, Nginx serves the built files using configuration from `deploy/nginx/`.
|
||||
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
|
||||
- `src/app/` - запуск приложения; `pages/`, `widgets/`, `features/`, `entities/` - слои интерфейса.
|
||||
- `src/shared/` - общие компоненты и API-клиент, включая сгенерированные endpoints, схемы Zod и MSW-моки.
|
||||
- `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта.
|
||||
- `scripts/` - проверки границ FSD.
|
||||
- `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2.
|
||||
|
||||
Из корня: `make -C frontend dev` запускает разработку, `make -C frontend check` - проверки и сборку. В Docker собранные файлы раздает Nginx с конфигурацией из `deploy/nginx/`.
|
||||
|
||||
|
||||
@@ -1,16 +1,70 @@
|
||||
import { defineConfig } from "orval";
|
||||
import { defineConfig, defineTransformer, type Options } from "orval";
|
||||
|
||||
export default defineConfig({
|
||||
lincodex: {
|
||||
const responseReferencePrefix = "#/components/responses/";
|
||||
|
||||
// Replaces each reference to components/responses with the referenced response
|
||||
// object. Schema, header, and example references inside it stay references.
|
||||
function inlineResponseReferences(
|
||||
value: unknown,
|
||||
responses: Readonly<Record<string, unknown>>,
|
||||
): unknown {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => inlineResponseReferences(item, responses));
|
||||
}
|
||||
if (value === null || typeof value !== "object") {
|
||||
return value;
|
||||
}
|
||||
|
||||
const reference = (value as { $ref?: unknown }).$ref;
|
||||
if (typeof reference === "string" && reference.startsWith(responseReferencePrefix)) {
|
||||
const name = reference.slice(responseReferencePrefix.length);
|
||||
if (!Object.hasOwn(responses, name)) {
|
||||
throw new Error(`Unknown response reference ${reference}.`);
|
||||
}
|
||||
return inlineResponseReferences(responses[name], responses);
|
||||
}
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, item]) => [key, inlineResponseReferences(item, responses)]),
|
||||
);
|
||||
}
|
||||
|
||||
// Orval 8.40 writes no Zod schema for components/responses entries, yet an
|
||||
// operation that references one imports a `<Name>Response` type that is never
|
||||
// generated. Inlining the references keeps the contract's reusable responses
|
||||
// while generated operations import only the component schemas Orval writes.
|
||||
const inlineReusableResponses = defineTransformer((spec) => {
|
||||
if (spec.paths === undefined) {
|
||||
return spec;
|
||||
}
|
||||
const responses = spec.components?.responses ?? {};
|
||||
return {
|
||||
...spec,
|
||||
paths: inlineResponseReferences(spec.paths, responses) as typeof spec.paths,
|
||||
};
|
||||
});
|
||||
|
||||
// The API compatibility check sets this variable to a temporary directory to
|
||||
// generate the OpenAPI 3.2 fixture with the production settings.
|
||||
const compatOutput = process.env["ORVAL_COMPAT_OUTPUT"];
|
||||
|
||||
function project(inputTarget: string, endpoints: string, schemas: string): Options {
|
||||
return {
|
||||
input: {
|
||||
target: "../../api/core/openapi.bundle.yml",
|
||||
target: inputTarget,
|
||||
override: {
|
||||
transformer: inlineReusableResponses,
|
||||
},
|
||||
},
|
||||
output: {
|
||||
mode: "tags-split",
|
||||
target: "../src/shared/api/endpoints",
|
||||
target: endpoints,
|
||||
indexFiles: true,
|
||||
// Generated operations take header parameters such as Idempotency-Key
|
||||
// and If-Match as a typed argument instead of dropping them.
|
||||
headers: true,
|
||||
schemas: {
|
||||
path: "../src/shared/api/schemas",
|
||||
path: schemas,
|
||||
type: "zod",
|
||||
splitByTags: true,
|
||||
},
|
||||
@@ -31,7 +85,31 @@ export default defineConfig({
|
||||
query: {
|
||||
signal: true,
|
||||
},
|
||||
// Optional properties are typed `{ x?: T }`, which the strict
|
||||
// exactOptionalPropertyTypes setting needs for optional header
|
||||
// parameters to fit RequestInit headers.
|
||||
zod: {
|
||||
exactOptional: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig(
|
||||
compatOutput === undefined
|
||||
? {
|
||||
lincodex: project(
|
||||
"../../api/core/openapi.bundle.yml",
|
||||
"../src/shared/api/endpoints",
|
||||
"../src/shared/api/schemas",
|
||||
),
|
||||
}
|
||||
: {
|
||||
compat: project(
|
||||
"../../api/testdata/openapi-3.2.0.yml",
|
||||
`${compatOutput}/endpoints`,
|
||||
`${compatOutput}/schemas`,
|
||||
),
|
||||
},
|
||||
);
|
||||
@@ -18,7 +18,8 @@
|
||||
"test": "vitest run",
|
||||
"test:fsd": "node ./scripts/test-fsd-boundaries.mjs",
|
||||
"check": "pnpm run fmt:check && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run test:fsd && pnpm run build",
|
||||
"verify": "pnpm run generate && pnpm run check"
|
||||
"verify": "pnpm run generate && pnpm run check",
|
||||
"check:orval-compat": "node ./scripts/check-orval-compat.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "5.104.1",
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// Generates the OpenAPI 3.2 compatibility fixture with the production Orval
|
||||
// settings into a temporary directory, type-checks the output with the
|
||||
// frontend compiler settings, and checks that the API conventions reached the
|
||||
// generated code. The directory is removed afterwards.
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
import { env, stdout } from "node:process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const bin = (name) => resolve(frontendRoot, "node_modules/.bin", name);
|
||||
|
||||
// Text that each fixture convention leaves in the generated TypeScript.
|
||||
const expectedFragments = {
|
||||
IdempotencyKey: '"Idempotency-Key": zod.string().min(1).max(',
|
||||
IfMatch: '"If-Match": zod.string().min(',
|
||||
PageLimit: '"limit": zod.int().min(1).max(',
|
||||
PageCursor: '"cursor": zod.string().min(1).max(',
|
||||
PageInfo: '"next_cursor": zod.string().min(1).max(',
|
||||
Timestamp: "export const Timestamp = zod.iso.datetime(",
|
||||
Problem: "export const Problem = zod.object(",
|
||||
ProblemErrorType: "TError = ErrorType<Problem>",
|
||||
HeaderArgument: "headers: CreateProbeItemHeaders",
|
||||
OptionalHeaderArgument: "headers: UpdateProbeItemHeaders",
|
||||
};
|
||||
|
||||
function run(command, args, extraEnv = {}) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: frontendRoot,
|
||||
encoding: "utf8",
|
||||
env: { ...env, ...extraEnv },
|
||||
});
|
||||
assert.equal(
|
||||
result.status,
|
||||
0,
|
||||
`${relative(frontendRoot, command)} failed:\n${result.stdout}\n${result.stderr}`,
|
||||
);
|
||||
}
|
||||
|
||||
function typeScriptFiles(directory) {
|
||||
return readdirSync(directory, { recursive: true, encoding: "utf8" })
|
||||
.filter((name) => name.endsWith(".ts"))
|
||||
.map((name) => join(directory, name));
|
||||
}
|
||||
|
||||
const outputDirectory = mkdtempSync(join(frontendRoot, ".orval-compat-"));
|
||||
try {
|
||||
run(bin("orval"), ["--config", "./codegen/orval.config.ts"], {
|
||||
ORVAL_COMPAT_OUTPUT: outputDirectory,
|
||||
});
|
||||
|
||||
const files = typeScriptFiles(outputDirectory);
|
||||
assert.ok(files.length > 0, "Orval generated no files for the compatibility fixture.");
|
||||
writeFileSync(
|
||||
join(outputDirectory, "tsconfig.json"),
|
||||
JSON.stringify({
|
||||
extends: "../tsconfig.json",
|
||||
files: files.map((file) => relative(outputDirectory, file)),
|
||||
}),
|
||||
);
|
||||
run(bin("tsc"), ["--noEmit", "-p", outputDirectory]);
|
||||
|
||||
const generated = files.map((file) => readFileSync(file, "utf8")).join("\n");
|
||||
for (const [component, fragment] of Object.entries(expectedFragments)) {
|
||||
assert.ok(generated.includes(fragment), `Generated code lacks ${component}: ${fragment}`);
|
||||
}
|
||||
stdout.write(`Orval compatibility fixture: ${files.length} files type-checked.\n`);
|
||||
} finally {
|
||||
rmSync(outputDirectory, { recursive: true, force: true });
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { apiRequest } from "./client";
|
||||
import { getHealthz } from "./endpoints/health/health";
|
||||
import {
|
||||
ApiRequestError,
|
||||
apiRequest,
|
||||
invalidResponseCode,
|
||||
networkErrorCode,
|
||||
unknownErrorCode,
|
||||
} from "./client";
|
||||
import { getHealthz, type GetHealthzQueryError } from "./endpoints/health/health";
|
||||
|
||||
const healthSchema = z.object({ status: z.literal("ok") });
|
||||
|
||||
@@ -53,31 +59,186 @@ describe("apiRequest", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("maps structured HTTP errors to a stable error type", async () => {
|
||||
it("maps an RFC 9457 problem response to ApiRequestError", async () => {
|
||||
const request = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
code: "service_unavailable",
|
||||
message: "Service unavailable",
|
||||
request_id: "req-test",
|
||||
type: "urn:lincodex:problem:validation_failed",
|
||||
title: "Request validation failed",
|
||||
status: 400,
|
||||
code: "validation_failed",
|
||||
detail: "One or more request fields are invalid.",
|
||||
trace_id: "0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10",
|
||||
errors: [
|
||||
{
|
||||
in: "query",
|
||||
pointer: "/limit",
|
||||
code: "invalid",
|
||||
message: "The value does not match the contract.",
|
||||
},
|
||||
],
|
||||
}),
|
||||
{
|
||||
status: 503,
|
||||
headers: { "content-type": "application/json" },
|
||||
status: 400,
|
||||
headers: { "content-type": "application/problem+json" },
|
||||
},
|
||||
),
|
||||
);
|
||||
vi.stubGlobal("fetch", request);
|
||||
|
||||
const error: unknown = await apiRequest("/healthz").catch((caught: unknown) => caught);
|
||||
|
||||
expect(error).toBeInstanceOf(ApiRequestError);
|
||||
expect(error).toMatchObject({
|
||||
name: "ApiRequestError",
|
||||
message: "One or more request fields are invalid.",
|
||||
status: 400,
|
||||
code: "validation_failed",
|
||||
title: "Request validation failed",
|
||||
detail: "One or more request fields are invalid.",
|
||||
traceId: "0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10",
|
||||
fieldErrors: [
|
||||
{
|
||||
in: "query",
|
||||
pointer: "/limit",
|
||||
code: "invalid",
|
||||
message: "The value does not match the contract.",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the title and the request ID header when the problem omits them", async () => {
|
||||
const request = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
type: "urn:lincodex:problem:forbidden",
|
||||
title: "Access denied",
|
||||
status: 403,
|
||||
code: "forbidden",
|
||||
}),
|
||||
{
|
||||
status: 403,
|
||||
headers: {
|
||||
"content-type": "application/problem+json; charset=utf-8",
|
||||
"x-request-id": "req-403",
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
vi.stubGlobal("fetch", request);
|
||||
|
||||
await expect(apiRequest("/healthz")).rejects.toMatchObject({
|
||||
name: "ApiRequestError",
|
||||
message: "Service unavailable",
|
||||
status: 503,
|
||||
code: "service_unavailable",
|
||||
requestId: "req-test",
|
||||
message: "Access denied",
|
||||
status: 403,
|
||||
code: "forbidden",
|
||||
detail: undefined,
|
||||
traceId: "req-403",
|
||||
fieldErrors: [],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "a JSON body that is not a problem",
|
||||
body: JSON.stringify({ code: "service_unavailable", message: "Service unavailable" }),
|
||||
contentType: "application/json",
|
||||
},
|
||||
{
|
||||
name: "a problem with an unknown code",
|
||||
body: JSON.stringify({
|
||||
type: "urn:lincodex:problem:new",
|
||||
title: "New",
|
||||
status: 503,
|
||||
code: "new",
|
||||
}),
|
||||
contentType: "application/problem+json",
|
||||
},
|
||||
{ name: "a proxy error page", body: "<html>Bad gateway</html>", contentType: "text/html" },
|
||||
])("falls back to http_error for $name", async ({ body, contentType }) => {
|
||||
const request = vi.fn().mockResolvedValue(
|
||||
new Response(body, {
|
||||
status: 503,
|
||||
headers: { "content-type": contentType, "x-request-id": "req-503" },
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", request);
|
||||
|
||||
await expect(apiRequest("/healthz")).rejects.toMatchObject({
|
||||
name: "ApiRequestError",
|
||||
message: "Request failed with status 503.",
|
||||
status: 503,
|
||||
code: unknownErrorCode,
|
||||
traceId: "req-503",
|
||||
fieldErrors: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps a network failure to ApiRequestError with status 0", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch")));
|
||||
|
||||
const error: unknown = await apiRequest("/healthz").catch((caught: unknown) => caught);
|
||||
|
||||
expect(error).toBeInstanceOf(ApiRequestError);
|
||||
expect(error).toMatchObject({ status: 0, code: networkErrorCode, fieldErrors: [] });
|
||||
});
|
||||
|
||||
it("lets a cancellation by the caller propagate unchanged", async () => {
|
||||
const controller = new AbortController();
|
||||
const abortError = new DOMException("The operation was aborted.", "AbortError");
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockImplementation(() => {
|
||||
controller.abort(abortError);
|
||||
return Promise.reject(abortError);
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(apiRequest("/healthz", { signal: controller.signal })).rejects.toBe(abortError);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "a body that is not JSON",
|
||||
body: "<html>ok</html>",
|
||||
schema: healthSchema,
|
||||
},
|
||||
{
|
||||
name: "a body that does not match the response schema",
|
||||
body: JSON.stringify({ status: "degraded" }),
|
||||
schema: healthSchema,
|
||||
},
|
||||
])("maps a 2xx response with $name to invalid_response", async ({ body, schema }) => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(body, {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json", "x-request-id": "req-200" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const error: unknown = await apiRequest("/healthz", {}, schema).catch(
|
||||
(caught: unknown) => caught,
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(ApiRequestError);
|
||||
expect(error).toMatchObject({ status: 200, code: invalidResponseCode, traceId: "req-200" });
|
||||
});
|
||||
|
||||
it("reports a cross-origin path as a programming error before any request", async () => {
|
||||
const request = vi.fn();
|
||||
vi.stubGlobal("fetch", request);
|
||||
|
||||
await expect(apiRequest("https://example.com/api/v1/healthz")).rejects.toThrow(TypeError);
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("types generated query errors as ApiRequestError", () => {
|
||||
expectTypeOf<GetHealthzQueryError>().toEqualTypeOf<ApiRequestError>();
|
||||
});
|
||||
|
||||
it("rejects an already-prefixed path before making a request", async () => {
|
||||
const request = vi.fn();
|
||||
vi.stubGlobal("fetch", request);
|
||||
|
||||
@@ -1,28 +1,73 @@
|
||||
import { z } from "zod";
|
||||
import type { z } from "zod";
|
||||
import { Problem, type ProblemCode, type ProblemFieldError } from "./schemas";
|
||||
|
||||
const apiPrefix = "/api/v1";
|
||||
const localOrigin = "http://lincodex.local";
|
||||
const problemMediaType = "application/problem+json";
|
||||
const requestIdHeader = "X-Request-ID";
|
||||
|
||||
const errorEnvelopeSchema = z
|
||||
.object({
|
||||
code: z.string().optional(),
|
||||
message: z.string().optional(),
|
||||
request_id: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
/** Code used when an error response is not a contract problem document. */
|
||||
export const unknownErrorCode = "http_error";
|
||||
/** Code used when the request did not produce an HTTP response. */
|
||||
export const networkErrorCode = "network_error";
|
||||
/** Code used when a 2xx response body is not valid JSON or does not match its schema. */
|
||||
export const invalidResponseCode = "invalid_response";
|
||||
|
||||
/**
|
||||
* Contract problem codes plus client-side codes that never appear in a
|
||||
* server response.
|
||||
*/
|
||||
export type ApiErrorCode =
|
||||
ProblemCode | typeof unknownErrorCode | typeof networkErrorCode | typeof invalidResponseCode;
|
||||
|
||||
type ApiRequestErrorInit = {
|
||||
status: number;
|
||||
code: ApiErrorCode;
|
||||
title: string;
|
||||
detail?: string | undefined;
|
||||
traceId?: string | undefined;
|
||||
fieldErrors?: readonly ProblemFieldError[] | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Error for every failed API request. For RFC 9457 problem responses it
|
||||
* carries the contract fields. `status` is 0 when no HTTP response arrived.
|
||||
*/
|
||||
export class ApiRequestError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status: number,
|
||||
readonly code: string,
|
||||
readonly requestId: string | undefined,
|
||||
) {
|
||||
super(message);
|
||||
readonly status: number;
|
||||
readonly code: ApiErrorCode;
|
||||
readonly title: string;
|
||||
readonly detail: string | undefined;
|
||||
readonly traceId: string | undefined;
|
||||
readonly fieldErrors: readonly ProblemFieldError[];
|
||||
|
||||
constructor(init: ApiRequestErrorInit) {
|
||||
super(init.detail ?? init.title);
|
||||
this.name = "ApiRequestError";
|
||||
this.status = init.status;
|
||||
this.code = init.code;
|
||||
this.title = init.title;
|
||||
this.detail = init.detail;
|
||||
this.traceId = init.traceId;
|
||||
this.fieldErrors = init.fieldErrors ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error type of generated query hooks. Orval passes the contract error schema
|
||||
* as the argument; the conditional only consumes it.
|
||||
*
|
||||
* apiRequest rejects with ApiRequestError for every request failure: an error
|
||||
* response, a network failure, and a 2xx body that is not valid JSON or does
|
||||
* not match its schema. It rejects with another error in two cases that are
|
||||
* not request failures: when the caller's AbortSignal cancels the request,
|
||||
* the original abort error propagates unchanged (TanStack Query treats it as
|
||||
* cancellation, not as a query error); and when a generated path is not a
|
||||
* same-origin /api/v1 path, a TypeError reports the programming error before
|
||||
* any request is sent.
|
||||
*/
|
||||
export type ErrorType<ContractError> = ContractError extends unknown ? ApiRequestError : never;
|
||||
|
||||
function buildApiUrl(path: string): string {
|
||||
const parsed = new URL(path, localOrigin);
|
||||
if (parsed.origin !== localOrigin) {
|
||||
@@ -40,25 +85,49 @@ function buildApiUrl(path: string): string {
|
||||
return `${pathname}${parsed.search}`;
|
||||
}
|
||||
|
||||
async function toApiError(response: Response): Promise<ApiRequestError> {
|
||||
const body: unknown = await response.json().catch(() => undefined);
|
||||
const parsed = errorEnvelopeSchema.safeParse(body);
|
||||
function isAbort(error: unknown, signal: AbortSignal | null | undefined): boolean {
|
||||
return signal?.aborted === true || (error instanceof DOMException && error.name === "AbortError");
|
||||
}
|
||||
|
||||
if (parsed.success) {
|
||||
return new ApiRequestError(
|
||||
parsed.data.message ?? `Request failed with status ${response.status}.`,
|
||||
response.status,
|
||||
parsed.data.code ?? "http_error",
|
||||
parsed.data.request_id,
|
||||
);
|
||||
function isProblemResponse(response: Response): boolean {
|
||||
const mediaType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
||||
return mediaType === problemMediaType;
|
||||
}
|
||||
|
||||
async function toApiError(response: Response): Promise<ApiRequestError> {
|
||||
const headerTraceId = response.headers.get(requestIdHeader) ?? undefined;
|
||||
|
||||
if (isProblemResponse(response)) {
|
||||
const body: unknown = await response.json().catch(() => undefined);
|
||||
const parsed = Problem.safeParse(body);
|
||||
if (parsed.success) {
|
||||
const problem = parsed.data;
|
||||
return new ApiRequestError({
|
||||
status: response.status,
|
||||
code: problem.code,
|
||||
title: problem.title,
|
||||
detail: problem.detail,
|
||||
traceId: problem.trace_id ?? headerTraceId,
|
||||
fieldErrors: problem.errors,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return new ApiRequestError(
|
||||
`Request failed with status ${response.status}.`,
|
||||
response.status,
|
||||
"http_error",
|
||||
undefined,
|
||||
);
|
||||
return new ApiRequestError({
|
||||
status: response.status,
|
||||
code: unknownErrorCode,
|
||||
title: `Request failed with status ${response.status}.`,
|
||||
traceId: headerTraceId,
|
||||
});
|
||||
}
|
||||
|
||||
function invalidResponseError(response: Response): ApiRequestError {
|
||||
return new ApiRequestError({
|
||||
status: response.status,
|
||||
code: invalidResponseCode,
|
||||
title: "The response does not match the API contract.",
|
||||
traceId: response.headers.get(requestIdHeader) ?? undefined,
|
||||
});
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(
|
||||
@@ -66,15 +135,41 @@ export async function apiRequest<T>(
|
||||
init: RequestInit = {},
|
||||
responseSchema?: z.ZodType<T>,
|
||||
): Promise<T> {
|
||||
const response = await fetch(buildApiUrl(path), {
|
||||
...init,
|
||||
credentials: "include",
|
||||
});
|
||||
const url = buildApiUrl(path);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(url, { ...init, credentials: "include" });
|
||||
} catch (error: unknown) {
|
||||
if (isAbort(error, init.signal)) {
|
||||
throw error;
|
||||
}
|
||||
throw new ApiRequestError({
|
||||
status: 0,
|
||||
code: networkErrorCode,
|
||||
title: "The request did not reach the server.",
|
||||
});
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw await toApiError(response);
|
||||
}
|
||||
|
||||
const body: unknown = response.status === 204 ? undefined : await response.json();
|
||||
return responseSchema ? responseSchema.parse(body) : (body as T);
|
||||
let body: unknown;
|
||||
try {
|
||||
body = response.status === 204 ? undefined : await response.json();
|
||||
} catch (error: unknown) {
|
||||
if (isAbort(error, init.signal)) {
|
||||
throw error;
|
||||
}
|
||||
throw invalidResponseError(response);
|
||||
}
|
||||
if (!responseSchema) {
|
||||
return body as T;
|
||||
}
|
||||
const parsed = responseSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
throw invalidResponseError(response);
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
@@ -20,10 +20,12 @@ import type {
|
||||
} from '@tanstack/react-query';
|
||||
|
||||
import type {
|
||||
HealthResponse
|
||||
HealthResponse,
|
||||
Problem
|
||||
} from '../../schemas';
|
||||
|
||||
import { apiRequest } from '../../client';
|
||||
import type { ErrorType } from '../../client';
|
||||
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
@@ -78,7 +80,7 @@ export const getGetHealthzQueryKey = () => {
|
||||
}
|
||||
|
||||
|
||||
export const getGetHealthzQueryOptions = <TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
export const getGetHealthzQueryOptions = <TData = Awaited<ReturnType<typeof getHealthz>>, TError = ErrorType<Problem>>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
) => {
|
||||
|
||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
@@ -97,10 +99,10 @@ const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
}
|
||||
|
||||
export type GetHealthzQueryResult = NonNullable<Awaited<ReturnType<typeof getHealthz>>>
|
||||
export type GetHealthzQueryError = unknown
|
||||
export type GetHealthzQueryError = ErrorType<Problem>
|
||||
|
||||
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = ErrorType<Problem>>(
|
||||
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>> & Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getHealthz>>,
|
||||
@@ -110,7 +112,7 @@ export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TE
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = ErrorType<Problem>>(
|
||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>> & Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getHealthz>>,
|
||||
@@ -120,7 +122,7 @@ export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TE
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = ErrorType<Problem>>(
|
||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
@@ -128,7 +130,7 @@ export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TE
|
||||
* @summary Check whether the API process is responding.
|
||||
*/
|
||||
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = ErrorType<Problem>>(
|
||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
||||
|
||||
@@ -1 +1,8 @@
|
||||
export { ApiRequestError, apiRequest } from "./client";
|
||||
export {
|
||||
ApiRequestError,
|
||||
apiRequest,
|
||||
invalidResponseCode,
|
||||
networkErrorCode,
|
||||
unknownErrorCode,
|
||||
type ApiErrorCode,
|
||||
} from "./client";
|
||||
@@ -6,3 +6,7 @@
|
||||
*/
|
||||
|
||||
export * from './healthResponse.zod';
|
||||
export * from './problem.zod';
|
||||
export * from './problemCode.zod';
|
||||
export * from './problemFieldError.zod';
|
||||
export * from './problemFieldLocation.zod';
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const problemTypeMax = 256;
|
||||
|
||||
export const problemTitleMax = 200;
|
||||
|
||||
export const problemStatusMin = 400;
|
||||
export const problemStatusMax = 599;
|
||||
|
||||
export const problemDetailMax = 1000;
|
||||
|
||||
export const problemInstanceMax = 2048;
|
||||
|
||||
export const problemTraceIdMax = 128;
|
||||
|
||||
|
||||
export const problemTraceIdRegExp = new RegExp('^[A-Za-z0-9._-]+$');
|
||||
export const problemErrorsItemPointerMax = 1024;
|
||||
|
||||
|
||||
export const problemErrorsItemPointerRegExp = new RegExp('^(/([^~/]|~[01])*)*$');
|
||||
export const problemErrorsItemCodeMax = 64;
|
||||
|
||||
|
||||
export const problemErrorsItemCodeRegExp = new RegExp('^[a-z][a-z0-9_]*$');
|
||||
export const problemErrorsItemMessageMax = 500;
|
||||
|
||||
export const problemErrorsMax = 100;
|
||||
|
||||
|
||||
export const Problem = zod.object({
|
||||
"type": zod.string().max(problemTypeMax).describe('URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.'),
|
||||
"title": zod.string().min(1).max(problemTitleMax).describe('Short, fixed English summary of the problem type. It does not change between occurrences.'),
|
||||
"status": zod.int().min(problemStatusMin).max(problemStatusMax).describe('HTTP status code generated by the origin server.'),
|
||||
"code": zod.enum(['validation_failed', 'unauthenticated', 'forbidden', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.'),
|
||||
"detail": zod.string().max(problemDetailMax).exactOptional().describe('Safe English explanation of this occurrence. It never contains internal error text or request values.'),
|
||||
"instance": zod.string().max(problemInstanceMax).exactOptional().describe('URI reference that identifies this occurrence, when one exists.'),
|
||||
"trace_id": zod.string().min(1).max(problemTraceIdMax).regex(problemTraceIdRegExp).exactOptional().describe('Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret.'),
|
||||
"errors": zod.array(zod.object({
|
||||
"in": zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.'),
|
||||
"pointer": zod.string().max(problemErrorsItemPointerMax).regex(problemErrorsItemPointerRegExp).describe('JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.'),
|
||||
"code": zod.string().min(1).max(problemErrorsItemCodeMax).regex(problemErrorsItemCodeRegExp).describe('Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.'),
|
||||
"message": zod.string().min(1).max(problemErrorsItemMessageMax).describe('Fixed English message that never echoes the submitted value.')
|
||||
}).describe('One reason why a request field or parameter is invalid.')).max(problemErrorsMax).exactOptional().describe('Field-level reasons for validation_failed. Other codes omit it.')
|
||||
}).describe('Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.')
|
||||
|
||||
export type Problem = zod.input<typeof Problem>;
|
||||
export type ProblemOutput = zod.output<typeof Problem>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const ProblemCode = zod.enum(['validation_failed', 'unauthenticated', 'forbidden', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.')
|
||||
|
||||
export type ProblemCode = zod.input<typeof ProblemCode>;
|
||||
export type ProblemCodeOutput = zod.output<typeof ProblemCode>;
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const problemFieldErrorPointerMax = 1024;
|
||||
|
||||
|
||||
export const problemFieldErrorPointerRegExp = new RegExp('^(/([^~/]|~[01])*)*$');
|
||||
export const problemFieldErrorCodeMax = 64;
|
||||
|
||||
|
||||
export const problemFieldErrorCodeRegExp = new RegExp('^[a-z][a-z0-9_]*$');
|
||||
export const problemFieldErrorMessageMax = 500;
|
||||
|
||||
|
||||
export const ProblemFieldError = zod.object({
|
||||
"in": zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.'),
|
||||
"pointer": zod.string().max(problemFieldErrorPointerMax).regex(problemFieldErrorPointerRegExp).describe('JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.'),
|
||||
"code": zod.string().min(1).max(problemFieldErrorCodeMax).regex(problemFieldErrorCodeRegExp).describe('Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.'),
|
||||
"message": zod.string().min(1).max(problemFieldErrorMessageMax).describe('Fixed English message that never echoes the submitted value.')
|
||||
}).describe('One reason why a request field or parameter is invalid.')
|
||||
|
||||
export type ProblemFieldError = zod.input<typeof ProblemFieldError>;
|
||||
export type ProblemFieldErrorOutput = zod.output<typeof ProblemFieldError>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const ProblemFieldLocation = zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.')
|
||||
|
||||
export type ProblemFieldLocation = zod.input<typeof ProblemFieldLocation>;
|
||||
export type ProblemFieldLocationOutput = zod.output<typeof ProblemFieldLocation>;
|
||||
@@ -5,4 +5,6 @@
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export * from './pageInfo.zod';
|
||||
export * from './timestamp.zod';
|
||||
export * from './health';
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const pageInfoNextCursorMax = 512;
|
||||
|
||||
|
||||
export const pageInfoNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
|
||||
|
||||
export const PageInfo = zod.object({
|
||||
"has_more": zod.boolean().describe('Whether another page follows this one.'),
|
||||
"next_cursor": zod.string().min(1).max(pageInfoNextCursorMax).regex(pageInfoNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.')
|
||||
}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.')
|
||||
|
||||
export type PageInfo = zod.input<typeof PageInfo>;
|
||||
export type PageInfoOutput = zod.output<typeof PageInfo>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const Timestamp = zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
|
||||
|
||||
export type Timestamp = zod.input<typeof Timestamp>;
|
||||
export type TimestampOutput = zod.output<typeof Timestamp>;
|
||||
Reference in new issue
Block a user