treat pathandinput as solid accessor

This commit is contained in:
OrJDev
2022-11-05 02:29:59 +02:00
parent df8aa2b9ec
commit efe56dc44d
6 changed files with 64 additions and 55 deletions
+9
View File
@@ -50,3 +50,12 @@ const App: Component<IAppProps> = ({}) => {
export default App; export default App;
``` ```
### Example
```ts
import { trpc } from "./utils/trpc";
import { createSignal } from "solid-js";
const [name, setName] = createSignal("");
const res = trpc.queryName.useQuery(() => ({ name: name() })); // this will be called when name changes
```
+1 -1
View File
@@ -3,7 +3,7 @@
"description": "SolidJS tRPC", "description": "SolidJS tRPC",
"author": "OrJDev", "author": "OrJDev",
"license": "MIT", "license": "MIT",
"version": "0.0.3-rc.1", "version": "0.0.4-rc.1",
"publishConfig": { "publishConfig": {
"access": "public", "access": "public",
"tag": "next" "tag": "next"
+7 -7
View File
@@ -44,8 +44,8 @@ export type DecorateProcedure<
TQueryFnData = inferProcedureOutput<TProcedure>, TQueryFnData = inferProcedureOutput<TProcedure>,
TData = inferProcedureOutput<TProcedure> TData = inferProcedureOutput<TProcedure>
>( >(
input: inferProcedureInput<TProcedure>, input: () => inferProcedureInput<TProcedure>,
opts?: UseTRPCQueryOptions< opts?: () => UseTRPCQueryOptions<
TPath, TPath,
inferProcedureInput<TProcedure>, inferProcedureInput<TProcedure>,
TQueryFnData, TQueryFnData,
@@ -59,8 +59,8 @@ export type DecorateProcedure<
_TQueryFnData = inferProcedureOutput<TProcedure>, _TQueryFnData = inferProcedureOutput<TProcedure>,
TData = inferProcedureOutput<TProcedure> TData = inferProcedureOutput<TProcedure>
>( >(
input: Omit<inferProcedureInput<TProcedure>, "cursor">, input: () => Omit<inferProcedureInput<TProcedure>, "cursor">,
opts?: UseTRPCInfiniteQueryOptions< opts?: () => UseTRPCInfiniteQueryOptions<
TPath, TPath,
inferProcedureInput<TProcedure>, inferProcedureInput<TProcedure>,
TData, TData,
@@ -75,7 +75,7 @@ export type DecorateProcedure<
: TProcedure extends AnyMutationProcedure : TProcedure extends AnyMutationProcedure
? { ? {
useMutation: <TContext = unknown>( useMutation: <TContext = unknown>(
opts?: UseTRPCMutationOptions< opts?: () => UseTRPCMutationOptions<
inferProcedureInput<TProcedure>, inferProcedureInput<TProcedure>,
TRPCClientErrorLike<TProcedure>, TRPCClientErrorLike<TProcedure>,
inferProcedureOutput<TProcedure>, inferProcedureOutput<TProcedure>,
@@ -91,8 +91,8 @@ export type DecorateProcedure<
: TProcedure extends AnySubscriptionProcedure : TProcedure extends AnySubscriptionProcedure
? { ? {
useSubscription: ( useSubscription: (
input: inferProcedureInput<TProcedure>, input: () => inferProcedureInput<TProcedure>,
opts?: UseTRPCSubscriptionOptions< opts?: () => UseTRPCSubscriptionOptions<
inferObservableValue<inferProcedureOutput<TProcedure>>, inferObservableValue<inferProcedureOutput<TProcedure>>,
TRPCClientErrorLike<TProcedure> TRPCClientErrorLike<TProcedure>
> >
+41 -42
View File
@@ -372,8 +372,11 @@ export function createHooksInternal<
TQueryFnData = TQueryValues[TPath]["output"], TQueryFnData = TQueryValues[TPath]["output"],
TData = TQueryValues[TPath]["output"] TData = TQueryValues[TPath]["output"]
>( >(
pathAndInput: [path: TPath, ...args: inferHandlerInput<TQueries[TPath]>], pathAndInput: () => [
opts?: UseTRPCQueryOptions< path: TPath,
...args: inferHandlerInput<TQueries[TPath]>
],
opts?: () => UseTRPCQueryOptions<
TPath, TPath,
TQueryValues[TPath]["input"], TQueryValues[TPath]["input"],
TQueryFnData, TQueryFnData,
@@ -382,25 +385,23 @@ export function createHooksInternal<
> >
): UseTRPCQueryResult<TData, TError> { ): UseTRPCQueryResult<TData, TError> {
const ctx = useContext(); const ctx = useContext();
if ( if (
typeof window === "undefined" && typeof window === "undefined" &&
ctx.ssrState() === "prepass" && ctx.ssrState() === "prepass" &&
opts?.trpc?.ssr !== false && opts?.().trpc?.ssr !== false &&
opts?.enabled !== false && opts?.().enabled !== false &&
!ctx.queryClient.getQueryCache().find(getArrayQueryKey(pathAndInput)) !ctx.queryClient.getQueryCache().find(getArrayQueryKey(pathAndInput()))
) { ) {
void ctx.prefetchQuery(pathAndInput as any, opts as any); void ctx.prefetchQuery(pathAndInput(), opts as any);
} }
const ssrOpts = useSSRQueryOptionsIfNeeded(pathAndInput, opts); const ssrOpts = useSSRQueryOptionsIfNeeded(pathAndInput(), opts?.());
// request option should take priority over global // request option should take priority over global
const shouldAbortOnUnmount = const shouldAbortOnUnmount =
opts?.trpc?.abortOnUnmount ?? ctx?.abortOnUnmount ?? false; opts?.().trpc?.abortOnUnmount ?? ctx?.abortOnUnmount ?? false;
const hook = __useQuery( const hook = __useQuery(
() => getArrayQueryKey(pathAndInput), () => getArrayQueryKey(pathAndInput()),
(queryFunctionContext) => { (queryFunctionContext) => {
const actualOpts = { const actualOpts = () => ({
...ssrOpts, ...ssrOpts,
trpc: { trpc: {
...ssrOpts?.trpc, ...ssrOpts?.trpc,
@@ -408,16 +409,16 @@ export function createHooksInternal<
? { signal: queryFunctionContext.signal } ? { signal: queryFunctionContext.signal }
: {}), : {}),
}, },
}; });
return (ctx.client as any).query( return (ctx.client as any).query(
...getClientArgs(pathAndInput, actualOpts) ...getClientArgs(pathAndInput(), actualOpts())
); );
}, },
{ context: SolidQueryContext, ...ssrOpts } as any { context: SolidQueryContext, ...ssrOpts } as any
) as UseTRPCQueryResult<TData, TError>; ) as UseTRPCQueryResult<TData, TError>;
hook.trpc = useHookResult({ hook.trpc = useHookResult({
path: pathAndInput[0], path: pathAndInput()[0],
}); });
return hook; return hook;
@@ -428,7 +429,7 @@ export function createHooksInternal<
TContext = unknown TContext = unknown
>( >(
path: TPath | [TPath], path: TPath | [TPath],
opts?: UseTRPCMutationOptions< opts?: () => UseTRPCMutationOptions<
TMutationValues[TPath]["input"], TMutationValues[TPath]["input"],
TError, TError,
TMutationValues[TPath]["output"], TMutationValues[TPath]["output"],
@@ -448,14 +449,14 @@ export function createHooksInternal<
const actualPath = Array.isArray(path) ? path[0] : path; const actualPath = Array.isArray(path) ? path[0] : path;
return (ctx.client.mutation as any)( return (ctx.client.mutation as any)(
...getClientArgs([actualPath, input], opts) ...getClientArgs([actualPath, input], opts?.())
); );
}, },
{ {
context: SolidQueryContext, context: SolidQueryContext,
...opts, ...opts?.(),
onSuccess(...args) { onSuccess(...args) {
const originalFn = () => opts?.onSuccess?.(...args); const originalFn = () => opts?.().onSuccess?.(...args);
return mutationSuccessOverride({ originalFn, queryClient }); return mutationSuccessOverride({ originalFn, queryClient });
}, },
} }
@@ -483,16 +484,16 @@ export function createHooksInternal<
TPath extends keyof TSubscriptions & string, TPath extends keyof TSubscriptions & string,
TOutput extends inferSubscriptionOutput<TRouter, TPath> TOutput extends inferSubscriptionOutput<TRouter, TPath>
>( >(
pathAndInput: [ pathAndInput: () => [
path: TPath, path: TPath,
...args: inferHandlerInput<TSubscriptions[TPath]> ...args: inferHandlerInput<TSubscriptions[TPath]>
], ],
opts: UseTRPCSubscriptionOptions< opts: () => UseTRPCSubscriptionOptions<
inferObservableValue<inferProcedureOutput<TSubscriptions[TPath]>>, inferObservableValue<inferProcedureOutput<TSubscriptions[TPath]>>,
inferProcedureClientError<TSubscriptions[TPath]> inferProcedureClientError<TSubscriptions[TPath]>
> >
) { ) {
const enabled = opts?.enabled ?? true; const enabled = opts?.().enabled ?? true;
const ctx = useContext(); const ctx = useContext();
return createEffect(() => { return createEffect(() => {
@@ -501,29 +502,28 @@ export function createHooksInternal<
} }
// noop // noop
(() => { (() => {
return hashQueryKey(pathAndInput); return hashQueryKey(pathAndInput());
})(); })();
const [path, input] = pathAndInput;
let isStopped = false; let isStopped = false;
const subscription = ctx.client.subscription< const subscription = ctx.client.subscription<
TRouter["_def"]["subscriptions"], TRouter["_def"]["subscriptions"],
TPath, TPath,
TOutput, TOutput,
inferProcedureInput<TRouter["_def"]["subscriptions"][TPath]> inferProcedureInput<TRouter["_def"]["subscriptions"][TPath]>
>(path, (input ?? undefined) as any, { >(pathAndInput()[0], (pathAndInput()[1] ?? undefined) as any, {
onStarted: () => { onStarted: () => {
if (!isStopped) { if (!isStopped) {
opts.onStarted?.(); opts?.().onStarted?.();
} }
}, },
onData: (data) => { onData: (data) => {
if (!isStopped) { if (!isStopped) {
opts.onData(data); opts().onData(data);
} }
}, },
onError: (err) => { onError: (err) => {
if (!isStopped) { if (!isStopped) {
opts.onError?.(err); opts().onError?.(err);
} }
}, },
}); });
@@ -535,40 +535,39 @@ export function createHooksInternal<
} }
function useInfiniteQuery<TPath extends TInfiniteQueryNames & string>( function useInfiniteQuery<TPath extends TInfiniteQueryNames & string>(
pathAndInput: [ pathAndInput: () => [
path: TPath, path: TPath,
input: Omit<TQueryValues[TPath]["input"], "cursor"> input: Omit<TQueryValues[TPath]["input"], "cursor">
], ],
opts?: UseTRPCInfiniteQueryOptions< opts?: () => UseTRPCInfiniteQueryOptions<
TPath, TPath,
Omit<TQueryValues[TPath]["input"], "cursor">, Omit<TQueryValues[TPath]["input"], "cursor">,
TQueryValues[TPath]["output"], TQueryValues[TPath]["output"],
TError TError
> >
): UseTRPCInfiniteQueryResult<TQueryValues[TPath]["output"], TError> { ): UseTRPCInfiniteQueryResult<TQueryValues[TPath]["output"], TError> {
const [path, input] = pathAndInput;
const ctx = useContext(); const ctx = useContext();
if ( if (
typeof window === "undefined" && typeof window === "undefined" &&
ctx.ssrState() === "prepass" && ctx.ssrState() === "prepass" &&
opts?.trpc?.ssr !== false && opts?.()?.trpc?.ssr !== false &&
opts?.enabled !== false && opts?.()?.enabled !== false &&
!ctx.queryClient.getQueryCache().find(getArrayQueryKey(pathAndInput)) !ctx.queryClient.getQueryCache().find(getArrayQueryKey(pathAndInput()))
) { ) {
void ctx.prefetchInfiniteQuery(pathAndInput as any, opts as any); void ctx.prefetchInfiniteQuery(pathAndInput as any, opts as any);
} }
const ssrOpts = useSSRQueryOptionsIfNeeded(pathAndInput, opts); const ssrOpts = useSSRQueryOptionsIfNeeded(pathAndInput(), opts?.());
// request option should take priority over global // request option should take priority over global
const shouldAbortOnUnmount = const shouldAbortOnUnmount =
opts?.trpc?.abortOnUnmount ?? ctx?.abortOnUnmount ?? false; opts?.()?.trpc?.abortOnUnmount ?? ctx?.abortOnUnmount ?? false;
const hook = __useInfiniteQuery( const hook = __useInfiniteQuery(
() => getArrayQueryKey(pathAndInput), () => getArrayQueryKey(pathAndInput()),
(queryFunctionContext) => { (queryFunctionContext) => {
const actualOpts = { const actualOpts = () => ({
...ssrOpts, ...ssrOpts,
trpc: { trpc: {
...ssrOpts?.trpc, ...ssrOpts?.trpc,
@@ -576,22 +575,22 @@ export function createHooksInternal<
? { signal: queryFunctionContext.signal } ? { signal: queryFunctionContext.signal }
: {}), : {}),
}, },
}; });
const actualInput = { const actualInput = {
...((input as any) ?? {}), ...((pathAndInput()[1] as any) ?? {}),
cursor: queryFunctionContext.pageParam, cursor: queryFunctionContext.pageParam,
}; };
return (ctx.client as any).query( return (ctx.client as any).query(
...getClientArgs([path, actualInput], actualOpts) ...getClientArgs([pathAndInput()[0], actualInput], actualOpts())
); );
}, },
{ context: SolidQueryContext, ...ssrOpts } as any { context: SolidQueryContext, ...ssrOpts } as any
) as UseTRPCInfiniteQueryResult<TQueryValues[TPath]["output"], TError>; ) as UseTRPCInfiniteQueryResult<TQueryValues[TPath]["output"], TError>;
hook.trpc = useHookResult({ hook.trpc = useHookResult({
path, path: pathAndInput()[0],
}); });
return hook; return hook;
} }
+4 -3
View File
@@ -26,8 +26,9 @@ export function createSolidProxyDecoration<
return (hooks as any)[lastArg](path, ...args); return (hooks as any)[lastArg](path, ...args);
} }
const [input, ...rest] = args; const [input, ...rest] = args;
return (hooks as any)[lastArg](
const queryKey = getQueryKey(path, input); () => getQueryKey(path, typeof input === "function" ? input() : input),
return (hooks as any)[lastArg](queryKey, ...rest); () => rest.map((arg) => (typeof arg === "function" ? arg() : arg))
);
}); });
} }
+2 -2
View File
@@ -3,7 +3,7 @@ import { QueryClient, QueryClientConfig } from "@tanstack/solid-query";
/** /**
* @internal * @internal
*/ */
export type CreateTRPCReactQueryClientConfig = export type CreateTRPCSolidQueryClientConfig =
| { | {
queryClient?: QueryClient; queryClient?: QueryClient;
queryClientConfig?: never; queryClientConfig?: never;
@@ -16,5 +16,5 @@ export type CreateTRPCReactQueryClientConfig =
/** /**
* @internal * @internal
*/ */
export const getQueryClient = (config: CreateTRPCReactQueryClientConfig) => export const getQueryClient = (config: CreateTRPCSolidQueryClientConfig) =>
config.queryClient ?? new QueryClient(config.queryClientConfig); config.queryClient ?? new QueryClient(config.queryClientConfig);