import type { BetterOmit, EmptyObject } from "./index.js"; import type { ConvexClient, ConvexHttpClient } from "convex/browser"; import type { FunctionArgs, FunctionReturnType } from "convex/server"; import type { FunctionReference } from "convex/server"; import type { Value } from "convex/values"; export type ArgsArray< Injected extends Record, FullArgs extends Injected, > = keyof FullArgs extends keyof Injected ? [args?: EmptyObject] : [args: BetterOmit]; /** * Inject arguments into a Convex client's calls. * * Useful when you want to pass an API key or session ID on many calls and don't * want to pass the value around and add it to the arguments explicitly. * * e.g. * ```ts * const client = new ConvexClient(process.env.CONVEX_URL!); * const apiClient = withArgs(client, { apiKey: process.env.API_KEY! }); * * const result = await apiClient.query(api.foo.bar, { ...other args }); * ``` * * @param client A ConvexClient instance * @param injectedArgs Arguments to inject into each query/mutation/action call. * @returns { query, mutation, action } functions with the injected arguments */ export function withArgs>( client: ConvexClient | ConvexHttpClient, injectedArgs: A, ) { return { query>( query: Query, ...args: ArgsArray> ): Promise>> { return client.query(query, { ...(args[0] ?? {}), ...injectedArgs, } as FunctionArgs); }, mutation>( mutation: Mutation, ...args: ArgsArray> ): Promise>> { return client.mutation(mutation, { ...(args[0] ?? {}), ...injectedArgs, } as FunctionArgs); }, action>( action: Action, ...args: ArgsArray> ): Promise>> { return client.action(action, { ...(args[0] ?? {}), ...injectedArgs, } as FunctionArgs); }, }; }