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
@@ -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