initial commit

This commit is contained in:
TakuyaYagam1 committed 2026-10-05 14:23:31 +03:00
commit 88c14b627e
224 files changed
+17204

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { z } from "zod";
import { apiRequest } from "./client";
import { getHealthz } from "./endpoints/health/health";
const healthSchema = z.object({ status: z.literal("ok") });
afterEach(() => {
vi.unstubAllGlobals();
});
describe("apiRequest", () => {
it("uses the shared request policy from generated operations", async () => {
const signal = new AbortController().signal;
const request = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ status: "ok" }), {
headers: { "content-type": "application/json" },
}),
);
vi.stubGlobal("fetch", request);
await expect(getHealthz({ signal })).resolves.toEqual({ status: "ok" });
expect(request).toHaveBeenCalledWith("/api/v1/healthz", {
signal,
method: "GET",
credentials: "include",
});
});
it("adds the API prefix once, sends cookies, and forwards cancellation", async () => {
const signal = new AbortController().signal;
const request = vi.fn().mockImplementation(() =>
Promise.resolve(
new Response(JSON.stringify({ status: "ok" }), {
headers: { "content-type": "application/json" },
}),
),
);
vi.stubGlobal("fetch", request);
const result = await apiRequest("/healthz", { signal }, healthSchema);
await apiRequest("/api/v1/healthz", {}, healthSchema);
expect(result).toEqual({ status: "ok" });
expect(request).toHaveBeenCalledTimes(2);
expect(request).toHaveBeenNthCalledWith(1, "/api/v1/healthz", {
signal,
credentials: "include",
});
expect(request).toHaveBeenNthCalledWith(2, "/api/v1/healthz", {
credentials: "include",
});
});
it("maps structured HTTP errors to a stable error type", async () => {
const request = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
code: "service_unavailable",
message: "Service unavailable",
request_id: "req-test",
}),
{
status: 503,
headers: { "content-type": "application/json" },
},
),
);
vi.stubGlobal("fetch", request);
await expect(apiRequest("/healthz")).rejects.toMatchObject({
name: "ApiRequestError",
message: "Service unavailable",
status: 503,
code: "service_unavailable",
requestId: "req-test",
});
});
it("rejects an already-prefixed path before making a request", async () => {
const request = vi.fn();
vi.stubGlobal("fetch", request);
await expect(apiRequest("/api/v1/api/v1/healthz")).rejects.toThrow(
"API paths must include the version prefix only once.",
);
expect(request).not.toHaveBeenCalled();
});
});
+80
View File
@@ -0,0 +1,80 @@
import { z } from "zod";
const apiPrefix = "/api/v1";
const localOrigin = "http://lincodex.local";
const errorEnvelopeSchema = z
.object({
code: z.string().optional(),
message: z.string().optional(),
request_id: z.string().optional(),
})
.passthrough();
export class ApiRequestError extends Error {
constructor(
message: string,
readonly status: number,
readonly code: string,
readonly requestId: string | undefined,
) {
super(message);
this.name = "ApiRequestError";
}
}
function buildApiUrl(path: string): string {
const parsed = new URL(path, localOrigin);
if (parsed.origin !== localOrigin) {
throw new TypeError("API requests must use the current origin.");
}
if (parsed.pathname.startsWith(`${apiPrefix}${apiPrefix}/`)) {
throw new TypeError("API paths must include the version prefix only once.");
}
const pathname =
parsed.pathname === apiPrefix || parsed.pathname.startsWith(`${apiPrefix}/`)
? parsed.pathname
: `${apiPrefix}${parsed.pathname}`;
return `${pathname}${parsed.search}`;
}
async function toApiError(response: Response): Promise<ApiRequestError> {
const body: unknown = await response.json().catch(() => undefined);
const parsed = errorEnvelopeSchema.safeParse(body);
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,
);
}
return new ApiRequestError(
`Request failed with status ${response.status}.`,
response.status,
"http_error",
undefined,
);
}
export async function apiRequest<T>(
path: string,
init: RequestInit = {},
responseSchema?: z.ZodType<T>,
): Promise<T> {
const response = await fetch(buildApiUrl(path), {
...init,
credentials: "include",
});
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);
}
@@ -0,0 +1,40 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import {
faker
} from '@faker-js/faker';
import {
HttpResponse,
http
} from 'msw';
import type {
RequestHandlerOptions
} from 'msw';
import type {
HealthResponse
} from '../../schemas';
export const getGetHealthzResponseMock = (overrideResponse: Partial<Extract<HealthResponse, object>> = {}): HealthResponse => ({status: faker.helpers.arrayElement(['ok'] as const), ...overrideResponse})
export const getGetHealthzMockHandler = (overrideResponse?: HealthResponse | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<HealthResponse> | HealthResponse), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/healthz', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getGetHealthzResponseMock(),
{ status: 200
})
}, options)
}
export const getHealthMock = () => [
getGetHealthzMockHandler()
]
@@ -0,0 +1,147 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import {
useQuery
} from '@tanstack/react-query';
import type {
DataTag,
DefinedInitialDataOptions,
DefinedUseQueryResult,
QueryClient,
QueryFunction,
QueryKey,
UndefinedInitialDataOptions,
UseQueryOptions,
UseQueryResult
} from '@tanstack/react-query';
import type {
HealthResponse
} from '../../schemas';
import { apiRequest } from '../../client';
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
const withQueryKey = <T extends object, K>(query: T, queryKey: K): T & { queryKey: K } => {
const result = { queryKey } as T & { queryKey: K };
for (const key of Object.keys(query)) {
// The explicit queryKey always wins, matching the previous
// `{ ...query, queryKey }` spread where it was set last.
if (key === 'queryKey') continue;
Object.defineProperty(result, key, {
enumerable: true,
configurable: true,
get: () => (query as Record<string, unknown>)[key],
});
}
return result;
};
export const getGetHealthzUrl = () => {
return `/api/v1/healthz`
}
/**
* @summary Check whether the API process is responding.
*/
export const getHealthz = async ( options?: Parameters<typeof apiRequest>[1]): Promise<HealthResponse> => {
return apiRequest<HealthResponse>(getGetHealthzUrl(),
{
...options,
method: 'GET'
}
);}
export const getGetHealthzQueryKey = () => {
return [
`/api/v1/healthz`
] as const;
}
export const getGetHealthzQueryOptions = <TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetHealthzQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof getHealthz>>> = ({ signal }) => getHealthz({ signal, ...requestOptions });
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetHealthzQueryResult = NonNullable<Awaited<ReturnType<typeof getHealthz>>>
export type GetHealthzQueryError = unknown
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getHealthz>>,
TError,
Awaited<ReturnType<typeof getHealthz>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getHealthz>>,
TError,
Awaited<ReturnType<typeof getHealthz>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary Check whether the API process is responding.
*/
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetHealthzQueryOptions(options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
@@ -0,0 +1 @@
export { getHealthMock } from './health/health.msw'
@@ -0,0 +1 @@
export * from './health/health';
+1
View File
@@ -0,0 +1 @@
export { ApiRequestError, apiRequest } from "./client";
+26
View File
@@ -0,0 +1,26 @@
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, expect, it, vi } from "vitest";
import { getHealthz } from "./endpoints/health/health";
import { getHealthMock } from "./endpoints/health/health.msw";
import { HealthResponse } from "./schemas";
const server = setupServer(...getHealthMock());
beforeAll(() => server.listen({ onUnhandledFrame: "error" }));
afterEach(() => {
vi.unstubAllGlobals();
server.resetHandlers();
});
afterAll(() => server.close());
it("serves the generated client through the generated MSW handler", async () => {
const interceptedFetch = globalThis.fetch;
// Node has no document origin for the browser client's relative URLs.
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
interceptedFetch(new URL(input, "http://localhost"), init),
);
const response = await getHealthz();
expect(HealthResponse.parse(response)).toEqual({ status: "ok" });
});
@@ -0,0 +1,14 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const HealthResponse = zod.object({
"status": zod.enum(['ok'])
})
export type HealthResponse = zod.input<typeof HealthResponse>;
export type HealthResponseOutput = zod.output<typeof HealthResponse>;
@@ -0,0 +1,8 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
export * from './healthResponse.zod';
+8
View File
@@ -0,0 +1,8 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
export * from './health';