feat: implement better api service

This commit is contained in:
ghost2023
2026-05-20 16:35:03 +03:00
parent 995030a72c
commit 028cf2aea8
2 changed files with 277 additions and 0 deletions

View File

@@ -1,3 +1,4 @@
import { QueryObserverOptions, UseQueryOptions } from "@tanstack/react-query";
import axios from "axios";
export const client = axios.create({
@@ -24,3 +25,88 @@ client.interceptors.response.use(
return Promise.reject(error);
},
);
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type QueryConfig<T> = Omit<
UseQueryOptions<T, Error, T, readonly unknown[]>,
"queryKey" | "queryFn"
>;
export interface EndpointWithInput<TInput, TResponse> {
call(input: TInput): Promise<TResponse>;
queryKey(): readonly unknown[];
queryKey(input: TInput): readonly unknown[];
queryOptions(
config: { input: TInput } & QueryConfig<TResponse>,
): UseQueryOptions<TResponse, Error, TResponse, readonly unknown[]>;
}
export interface EndpointWithoutInput<TResponse> {
call(): Promise<TResponse>;
queryKey(): readonly unknown[];
queryOptions(
config?: QueryConfig<TResponse>,
): UseQueryOptions<TResponse, Error, TResponse, readonly unknown[]>;
}
export type Endpoint<TInput, TResponse> = TInput extends void
? EndpointWithoutInput<TResponse>
: EndpointWithInput<TInput, TResponse>;
// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------
export function endpoint<TInput, TResponse>(
service: string,
action: string,
execute: (input: TInput) => Promise<TResponse>,
): Endpoint<TInput, TResponse> {
const call = (input: TInput) => execute(input);
const queryKey = (input?: TInput): readonly unknown[] => {
if (input === undefined) return [service, action] as const;
return [service, action, input] as const;
};
const queryOptions = (
config?: Record<string, unknown>,
): QueryObserverOptions<
TResponse,
Error,
TResponse,
TResponse,
readonly unknown[]
> => {
const input = config?.input as TInput | undefined;
const { input: _, ...rest } = config ?? {};
const key: readonly unknown[] =
input !== undefined ? [service, action, input] : [service, action];
return {
...rest,
queryKey: key,
queryFn: () => execute(input as TInput),
} as ReturnType<typeof queryOptions>;
};
return { call, queryKey, queryOptions } as Endpoint<TInput, TResponse>;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/** Some API endpoints return `{ data: T }`, others return `T` directly. */
export function unwrap<T>(response: { data: T } | T): T {
if (
response &&
typeof response === "object" &&
"data" in (response as object)
) {
return (response as { data: T }).data;
}
return response as T;
}