refactor: migrate to use the central api obj

This commit is contained in:
Nathnael
2026-06-22 11:52:59 +00:00
parent 71db3a968e
commit 74e03f2067
8 changed files with 805 additions and 105 deletions

View File

@@ -12,6 +12,27 @@ export type QueryConfig<T> = Omit<
"queryKey" | "queryFn"
>;
/**
* Query keys a mutation should invalidate on success. Receives the mutation
* input and response so keys can be derived from them. Returns a list of query
* keys — each is matched as a *prefix* by React Query, so returning a service
* root (e.g. `["cargoes"]`) invalidates every query nested under it.
*
* The keys are surfaced through `mutationOptions().meta.invalidates`; the
* app-wide `MutationCache` (see `lib/queryClient.ts`) reads them and invalidates
* automatically, so components never wire `onSuccess` invalidation by hand.
*/
export type InvalidatesFn<TInput, TResponse> = (
input: TInput,
data: TResponse,
) => ReadonlyArray<readonly unknown[]>;
/** Shape stored in `mutation.meta.invalidates` and consumed by the MutationCache. */
export type InvalidatesMeta = (
variables: unknown,
data: unknown,
) => ReadonlyArray<readonly unknown[]>;
// ---------------------------------------------------------------------------
// Endpoint interfaces
// ---------------------------------------------------------------------------
@@ -45,6 +66,7 @@ export function endpoint<TInput, TResponse>(
action: string,
execute: (input: TInput) => Promise<TResponse>,
queryKeyBuilder?: (input: TInput) => readonly unknown[],
invalidates?: InvalidatesFn<TInput, TResponse>,
) {
const buildKey = (input?: TInput): readonly unknown[] => {
if (queryKeyBuilder && input !== undefined) {
@@ -77,27 +99,25 @@ export function endpoint<TInput, TResponse>(
};
const mutationOptions = (
config?: Omit<
UseMutationOptions<
TResponse,
Error,
TInput
>,
"mutationFn"
>,
): UseMutationOptions<
TResponse,
Error,
TInput
> => {
return {
...config,
mutationFn: (
variables: TInput,
): Promise<TResponse> =>
execute(variables),
config?: Omit<UseMutationOptions<TResponse, Error, TInput>, "mutationFn">,
): UseMutationOptions<TResponse, Error, TInput> => {
const meta = invalidates
? {
...config?.meta,
invalidates: ((variables, data) =>
invalidates(
variables as TInput,
data as TResponse,
)) satisfies InvalidatesMeta,
}
: config?.meta;
return {
...config,
meta,
mutationFn: (variables: TInput): Promise<TResponse> => execute(variables),
};
};
};
return {
call,