Skip to content

Commit a2605d1

Browse files
committed
prefetchFindFirst
1 parent d17fd26 commit a2605d1

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

src/lib/prefetch-queries.ts

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
import { AnyUseQueryOptions, type QueryClient } from "@tanstack/react-query"
2-
import { type BuildQueryResult, type DBQueryConfig, type TablesRelationalConfig } from "drizzle-orm"
2+
import {
3+
type BuildQueryResult,
4+
type DBQueryConfig,
5+
type TablesRelationalConfig,
6+
eq,
7+
sql
8+
} from "drizzle-orm"
39
import { type PgDatabase, type PgQueryResultHKT } from "drizzle-orm/pg-core"
410

5-
import { findMany } from "./db-queries"
11+
import { findFirst, findMany } from "./db-queries"
612
import { serializeConfig } from "./utils"
713

814
export async function prefetchFindMany<
@@ -20,7 +26,7 @@ export async function prefetchFindMany<
2026
) {
2127
type TableType = BuildQueryResult<TSchema, TSchema[TableName], TConfig>
2228

23-
if (process.env.NODE_ENV === "development") await new Promise((resolve) => setTimeout(resolve, 200))
29+
if (process.env.NODE_ENV === "development") await new Promise((resolve) => setTimeout(resolve, 250))
2430

2531
const queryKey = [table, "list", ...(config ? [serializeConfig(config)] : [])]
2632
const results = await findMany(db, table, config)
@@ -34,4 +40,41 @@ export async function prefetchFindMany<
3440
})
3541

3642
return results as TableType[]
43+
}
44+
45+
export async function prefetchFindFirst<
46+
TQueryResult extends PgQueryResultHKT,
47+
TFullSchema extends Record<string, unknown>,
48+
TSchema extends TablesRelationalConfig,
49+
TableName extends keyof TSchema,
50+
TConfig extends DBQueryConfig<"one", true, TSchema, TSchema[TableName]>,
51+
IDType = TSchema[TableName]["columns"]["id"]["_"]["data"]
52+
>(
53+
db: PgDatabase<TQueryResult, TFullSchema, TSchema>,
54+
queryClient: QueryClient,
55+
table: TableName,
56+
id?: IDType | null,
57+
config?: TConfig | null,
58+
options?: Omit<AnyUseQueryOptions, "queryKey" | "queryFn"> | null
59+
) {
60+
type TableType = BuildQueryResult<TSchema, TSchema[TableName], TConfig>
61+
62+
if (process.env.NODE_ENV === "development") await new Promise((resolve) => setTimeout(resolve, 250))
63+
64+
const queryKey = [table, "detail", id, ...((!id && config) ? [serializeConfig(config)] : [])]
65+
66+
const result = await findFirst(db, table, {
67+
where: id ? eq(sql`id`, id) : undefined,
68+
...config
69+
})
70+
71+
queryClient.prefetchQuery<TableType>({
72+
...options,
73+
queryKey,
74+
queryFn: async () => {
75+
return result as TableType
76+
}
77+
})
78+
79+
return result as TableType
3780
}

0 commit comments

Comments
 (0)