1
1
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"
3
9
import { type PgDatabase , type PgQueryResultHKT } from "drizzle-orm/pg-core"
4
10
5
- import { findMany } from "./db-queries"
11
+ import { findFirst , findMany } from "./db-queries"
6
12
import { serializeConfig } from "./utils"
7
13
8
14
export async function prefetchFindMany <
@@ -20,7 +26,7 @@ export async function prefetchFindMany<
20
26
) {
21
27
type TableType = BuildQueryResult < TSchema , TSchema [ TableName ] , TConfig >
22
28
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 ) )
24
30
25
31
const queryKey = [ table , "list" , ...( config ? [ serializeConfig ( config ) ] : [ ] ) ]
26
32
const results = await findMany ( db , table , config )
@@ -34,4 +40,41 @@ export async function prefetchFindMany<
34
40
} )
35
41
36
42
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
37
80
}
0 commit comments