Created
January 31, 2025 23:28
-
-
Save jkcorrea/d9b061a66994d18fabab46107ae926ed to your computer and use it in GitHub Desktop.
TRPC query inputs helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { AnyProcedure, AnyQueryProcedure, inferProcedureInput } from '@trpc/server' | |
import { trpc, type AppRouter } from './trpc' | |
interface RouterRecord { | |
[key: string]: AnyProcedure | RouterRecord | |
} | |
type getQueryInput<T extends AnyQueryProcedure> = | |
| inferProcedureInput<T> | |
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | |
| ((...args: any[]) => inferProcedureInput<T>) | |
type Queries<TRecord extends RouterRecord> = { | |
[TKey in keyof TRecord]?: TRecord[TKey] extends AnyQueryProcedure | |
? Record<string, getQueryInput<TRecord[TKey]>> | |
: TRecord[TKey] extends RouterRecord | |
? Queries<TRecord[TKey]> | |
: never | |
} | |
// Define queries | |
const queries = { | |
reports: { | |
revenue: { | |
fetch: { | |
// name these anything you want | |
default: { | |
from: new Date('2024-01-01'), | |
to: new Date('2024-01-31'), | |
}, | |
between: (from: Date, to: Date) => ({ | |
from, | |
to, | |
}), | |
}, | |
}, | |
}, | |
} as const satisfies Queries<AppRouter['_def']['record']> | |
// Grab query options | |
// const queryOptions1 = queries.reports.revenue.fetch.default | |
// const queryOptions2 = queries.reports.revenue.fetch.between( | |
// new Date('2024-01-01'), | |
// new Date('2024-01-31'), | |
// ) | |
// | |
// Use them anywhere! | |
// const revenue1 = trpc.reports.revenue.fetch.useQuery(queryOptions1) | |
// const revenue2 = trpc.reports.revenue.fetch.useQuery(queryOptions2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment