@supatype/react 0.9.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +18 -13
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +18 -0
- package/dist/useAuth.d.ts +6 -1
- package/dist/useAuth.d.ts.map +1 -1
- package/dist/useAuth.js +26 -12
- package/dist/useAuth.js.map +1 -1
- package/dist/useFunction.d.ts.map +1 -1
- package/dist/useFunction.js +7 -1
- package/dist/useFunction.js.map +1 -1
- package/dist/useMutation.d.ts.map +1 -1
- package/dist/useMutation.js +6 -1
- package/dist/useMutation.js.map +1 -1
- package/dist/useQuery.d.ts +1 -1
- package/dist/useQuery.d.ts.map +1 -1
- package/dist/useQuery.js +85 -59
- package/dist/useQuery.js.map +1 -1
- package/dist/useSubscription.d.ts +5 -0
- package/dist/useSubscription.d.ts.map +1 -1
- package/dist/useSubscription.js +8 -3
- package/dist/useSubscription.js.map +1 -1
- package/package.json +3 -3
- package/src/useAuth.ts +43 -13
- package/src/useFunction.ts +6 -1
- package/src/useMutation.ts +5 -1
- package/src/useQuery.ts +99 -63
- package/src/useSubscription.ts +13 -3
- package/tests/stable-callbacks.test.tsx +123 -0
- package/tests/thrown-errors.test.tsx +163 -0
- package/tests/useAuth-sso.test.tsx +67 -0
- package/tests/useMutation-requests.test.tsx +13 -3
- package/tests/useQuery-enabled.test.tsx +94 -0
- package/tests/useQuery-race.test.tsx +98 -0
- package/tests/useSubscription-error.test.tsx +56 -0
- package/tests/useSubscription-schema.test.tsx +56 -0
- package/tsconfig.tsbuildinfo +1 -1
package/src/useAuth.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
|
|
3
|
-
import { useState, useEffect } from "react"
|
|
4
|
-
import type {
|
|
3
|
+
import { useState, useEffect, useMemo } from "react"
|
|
4
|
+
import type {
|
|
5
|
+
AuthClient,
|
|
6
|
+
Session,
|
|
7
|
+
SignInWithSSOCredentials,
|
|
8
|
+
SignInWithSSOResult,
|
|
9
|
+
User,
|
|
10
|
+
AuthChangeEvent,
|
|
11
|
+
AuthRedirectError,
|
|
12
|
+
SupatypeError,
|
|
13
|
+
} from "@supatype/client"
|
|
5
14
|
import { useSupatype } from "./context.js"
|
|
15
|
+
import { reportThrown } from "@supatype/client/bindings"
|
|
6
16
|
|
|
7
17
|
export interface UseAuthReturn {
|
|
8
18
|
/** The currently authenticated user, or null if not signed in. */
|
|
@@ -32,6 +42,11 @@ export interface UseAuthReturn {
|
|
|
32
42
|
provider: string
|
|
33
43
|
options?: { redirectTo?: string } | undefined
|
|
34
44
|
}): Promise<{ data: { url: string; provider: string }; error: SupatypeError | null }>
|
|
45
|
+
/**
|
|
46
|
+
* Sign in with SAML single sign-on, by email domain or provider ID: sends the browser to the
|
|
47
|
+
* identity provider unless `skipBrowserRedirect`, and returns its URL.
|
|
48
|
+
*/
|
|
49
|
+
signInWithSSO(params: SignInWithSSOCredentials): Promise<SignInWithSSOResult>
|
|
35
50
|
/** Sign in with a magic link (OTP) sent to the email. */
|
|
36
51
|
signInWithOtp(opts: {
|
|
37
52
|
email: string
|
|
@@ -68,6 +83,12 @@ export function useAuth(): UseAuthReturn {
|
|
|
68
83
|
setSession(data.session)
|
|
69
84
|
setError(redirectError)
|
|
70
85
|
setLoading(false)
|
|
86
|
+
}).catch((e: unknown) => {
|
|
87
|
+
// Starting threw (a client with no API address, say): there is no session to wait for.
|
|
88
|
+
const thrown = reportThrown("useAuth", e)
|
|
89
|
+
if (!active) return
|
|
90
|
+
setError(thrown)
|
|
91
|
+
setLoading(false)
|
|
71
92
|
})
|
|
72
93
|
|
|
73
94
|
// Subscribe to future changes
|
|
@@ -81,15 +102,24 @@ export function useAuth(): UseAuthReturn {
|
|
|
81
102
|
}
|
|
82
103
|
}, [client])
|
|
83
104
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
105
|
+
const methods = useAuthMethods(client.auth)
|
|
106
|
+
return { user: session?.user ?? null, session, loading, error, ...methods }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
type AuthMethods = Omit<UseAuthReturn, "user" | "session" | "loading" | "error">
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The sign-in and sign-out calls, made once per auth client so each keeps its identity across
|
|
113
|
+
* renders and can be an effect dependency (0.9.1 release test, RB10: `useQuery`'s `refetch` was
|
|
114
|
+
* rebuilt every render and looped an effect that listed it).
|
|
115
|
+
*/
|
|
116
|
+
function useAuthMethods(auth: AuthClient): AuthMethods {
|
|
117
|
+
return useMemo<AuthMethods>(() => ({
|
|
118
|
+
signUp: (creds) => auth.signUp(creds),
|
|
119
|
+
signIn: (creds) => auth.signInWithPassword(creds),
|
|
120
|
+
signInWithOAuth: (opts) => auth.signInWithOAuth(opts),
|
|
121
|
+
signInWithSSO: (params) => auth.signInWithSSO(params),
|
|
122
|
+
signInWithOtp: (opts) => auth.signInWithOtp(opts),
|
|
123
|
+
signOut: () => auth.signOut(),
|
|
124
|
+
}), [auth])
|
|
95
125
|
}
|
package/src/useFunction.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { useState, useCallback } from "react"
|
|
4
4
|
import type { AnyDatabase, AugmentedDatabase, SupatypeError } from "@supatype/client"
|
|
5
5
|
import { useSupatype } from "./context.js"
|
|
6
|
-
import { isCallerValue } from "@supatype/client/bindings"
|
|
6
|
+
import { isCallerValue, reportThrown } from "@supatype/client/bindings"
|
|
7
7
|
|
|
8
8
|
export interface FunctionCallOptions {
|
|
9
9
|
/** HTTP method. Default: POST */
|
|
@@ -64,6 +64,11 @@ export function useFunction<
|
|
|
64
64
|
setData(answer.data)
|
|
65
65
|
if (answer.error !== null) setError(answer.error)
|
|
66
66
|
return answer
|
|
67
|
+
} catch (e) {
|
|
68
|
+
const thrown = reportThrown(`useFunction("${functionName}")`, e)
|
|
69
|
+
setData(null)
|
|
70
|
+
setError(thrown)
|
|
71
|
+
return { data: null, error: thrown }
|
|
67
72
|
} finally {
|
|
68
73
|
setLoading(false)
|
|
69
74
|
}
|
package/src/useMutation.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { useState, useCallback } from "react"
|
|
4
4
|
import type { AnyClient, AnyDatabase, AugmentedDatabase, SupatypeError } from "@supatype/client"
|
|
5
5
|
import { useSupatype } from "./context.js"
|
|
6
|
-
import { runMutation, type MutationOperation, type MutationOutcome, type MutationRequest } from "@supatype/client/bindings"
|
|
6
|
+
import { reportThrown, runMutation, type MutationOperation, type MutationOutcome, type MutationRequest } from "@supatype/client/bindings"
|
|
7
7
|
|
|
8
8
|
export type { MutationOperation }
|
|
9
9
|
|
|
@@ -61,6 +61,10 @@ export function useMutation<
|
|
|
61
61
|
const result = await runMutation<TRow>(client as AnyClient, table, operation, data, options)
|
|
62
62
|
if (result.error !== null) setError(result.error)
|
|
63
63
|
return result
|
|
64
|
+
} catch (e) {
|
|
65
|
+
const thrown = reportThrown(`useMutation("${table}", "${operation}")`, e)
|
|
66
|
+
setError(thrown)
|
|
67
|
+
return { data: null, error: thrown, count: null }
|
|
64
68
|
} finally {
|
|
65
69
|
setLoading(false)
|
|
66
70
|
}
|
package/src/useQuery.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { useState, useEffect, useCallback, useRef } from "react"
|
|
|
4
4
|
import type { AnyClient, AnyDatabase, AugmentedDatabase, SupatypeError, QueryCacheOptions } from "@supatype/client"
|
|
5
5
|
import { onIdentityChange } from "@supatype/client"
|
|
6
6
|
import { useSupatype } from "./context.js"
|
|
7
|
-
import { isRowsOf } from "@supatype/client/bindings"
|
|
7
|
+
import { isRowsOf, reportThrown, withPage } from "@supatype/client/bindings"
|
|
8
8
|
|
|
9
9
|
export interface UseQueryOptions {
|
|
10
10
|
/** PostgREST select expression (default: '*') */
|
|
@@ -15,7 +15,7 @@ export interface UseQueryOptions {
|
|
|
15
15
|
order?: { column: string; ascending?: boolean | undefined } | undefined
|
|
16
16
|
/** Maximum number of rows to return */
|
|
17
17
|
limit?: number | undefined
|
|
18
|
-
/** Row offset (for pagination) */
|
|
18
|
+
/** Row offset (for pagination). With no `limit`, a page of 100 rows is read from it. */
|
|
19
19
|
offset?: number | undefined
|
|
20
20
|
/** Set to false to skip the query (useful for conditional fetching) */
|
|
21
21
|
enabled?: boolean | undefined
|
|
@@ -69,81 +69,117 @@ export function useQuery<
|
|
|
69
69
|
options?: UseQueryOptions | undefined,
|
|
70
70
|
): UseQueryResult<TRow> {
|
|
71
71
|
const client = useSupatype<TDatabase>()
|
|
72
|
-
const [
|
|
73
|
-
const
|
|
74
|
-
const [count, setCount] = useState<number | null>(null)
|
|
75
|
-
const [loading, setLoading] = useState(true)
|
|
72
|
+
const [state, setState] = useState<RowsState<TRow>>({ data: null, error: null, count: null, loading: false, answered: null })
|
|
73
|
+
const latest = useRef(0)
|
|
76
74
|
|
|
77
|
-
//
|
|
78
|
-
|
|
79
|
-
const
|
|
75
|
+
// Which read this render asks for. A string, so a caller's inline options object, new on every
|
|
76
|
+
// render, does not count as a new read.
|
|
77
|
+
const key = JSON.stringify([table, options])
|
|
80
78
|
|
|
81
79
|
const execute = useCallback(async () => {
|
|
80
|
+
const request = ++latest.current
|
|
81
|
+
// Only the latest request is shown: an older one that lands after it is dropped, whatever it
|
|
82
|
+
// brought, so it cannot replace newer rows or an error the newer request did not have.
|
|
83
|
+
const show = (next: Partial<RowsState<TRow>>): void => {
|
|
84
|
+
if (request === latest.current) setState((current) => ({ ...current, ...next }))
|
|
85
|
+
}
|
|
82
86
|
if (options?.enabled === false) {
|
|
83
|
-
|
|
87
|
+
show({ loading: false })
|
|
84
88
|
return
|
|
85
89
|
}
|
|
86
|
-
|
|
90
|
+
show({ loading: true })
|
|
91
|
+
show({ ...(await settledRows<TRow>(client as AnyClient, table, options)), answered: key })
|
|
92
|
+
// `key` stands in for `table` and `options`: a caller's inline object is new on every render,
|
|
93
|
+
// and depending on it would read again on every render.
|
|
94
|
+
}, [client, key])
|
|
87
95
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const source = (client as AnyClient).from(table)
|
|
91
|
-
// A draft read is the same request against a different schema, so it branches here rather than
|
|
92
|
-
// duplicating every filter below.
|
|
93
|
-
let query = (options?.draft === true ? source.draft() : source).select(
|
|
94
|
-
options?.select ?? "*",
|
|
95
|
-
)
|
|
96
|
+
useRunAndRefetch(execute, options?.refetchInterval)
|
|
97
|
+
useRerunOnIdentityChange(client.auth, execute)
|
|
96
98
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
}
|
|
105
|
-
if (options?.limit !== undefined) {
|
|
106
|
-
query = query.limit(options.limit)
|
|
107
|
-
}
|
|
108
|
-
if (options?.offset !== undefined && options.limit !== undefined) {
|
|
109
|
-
query = query.range(options.offset, options.offset + options.limit - 1)
|
|
110
|
-
}
|
|
111
|
-
if (options?.cache !== undefined) {
|
|
112
|
-
query = query.cache(options.cache)
|
|
113
|
-
}
|
|
99
|
+
// Changes only when the query does, so an app can list it as an effect dependency. 0.9.1 release
|
|
100
|
+
// test (RB10): a new function each render made `useEffect(() => refetch(), [refetch])` loop.
|
|
101
|
+
const refetch = useCallback(() => void execute(), [execute])
|
|
102
|
+
|
|
103
|
+
const { data, error, count } = state
|
|
104
|
+
return { data, error, count, loading: isLoading(state, key, options?.enabled), refetch }
|
|
105
|
+
}
|
|
114
106
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
107
|
+
/** What the hook shows: the latest request's answer, and whether one is in flight. */
|
|
108
|
+
interface RowsState<TRow> {
|
|
109
|
+
data: TRow[] | null
|
|
110
|
+
error: SupatypeError | null
|
|
111
|
+
count: number | null
|
|
112
|
+
loading: boolean
|
|
113
|
+
/** The key of the read whose answer `data` holds, or null before any has arrived. */
|
|
114
|
+
answered: string | null
|
|
115
|
+
}
|
|
122
116
|
|
|
117
|
+
/**
|
|
118
|
+
* Loading, worked out while rendering rather than set by the effect that starts the read. 0.9.2
|
|
119
|
+
* release test (N-FF9): set by the effect, the render where `enabled` turned true, or the options
|
|
120
|
+
* changed, still said `loading: false` with no rows for the new key, which an app reads as "done,
|
|
121
|
+
* nothing found". Until the answer for this key arrives, an enabled query is loading.
|
|
122
|
+
*/
|
|
123
|
+
function isLoading<TRow>(state: RowsState<TRow>, key: string, enabled: boolean | undefined): boolean {
|
|
124
|
+
return enabled !== false && (state.loading || state.answered !== key)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The read's answer as the hook shows it. A request that throws (a client with no API address, say)
|
|
129
|
+
* ends like one that was refused, and is reported even when a newer request has replaced it.
|
|
130
|
+
*/
|
|
131
|
+
async function settledRows<TRow>(
|
|
132
|
+
client: AnyClient,
|
|
133
|
+
table: string,
|
|
134
|
+
options: UseQueryOptions | undefined,
|
|
135
|
+
): Promise<Omit<RowsState<TRow>, "answered">> {
|
|
136
|
+
try {
|
|
137
|
+
const result = await readRows(client, table, options)
|
|
138
|
+
return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error, count: result.count, loading: false }
|
|
139
|
+
} catch (e) {
|
|
140
|
+
return { data: null, error: reportThrown(`useQuery("${table}")`, e), count: null, loading: false }
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Run `execute` now and whenever it changes, and every `interval` milliseconds when one is set. */
|
|
145
|
+
function useRunAndRefetch(execute: () => Promise<void>, interval: number | undefined): void {
|
|
123
146
|
useEffect(() => {
|
|
124
147
|
void execute()
|
|
148
|
+
if (interval === undefined) return undefined
|
|
149
|
+
const timer = setInterval(() => void execute(), interval)
|
|
150
|
+
return () => clearInterval(timer)
|
|
151
|
+
}, [execute, interval])
|
|
152
|
+
}
|
|
125
153
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
136
|
-
}, [execute])
|
|
137
|
-
|
|
138
|
-
// Re-run when the signed-in identity changes. See `onIdentityChange` for which changes count.
|
|
139
|
-
//
|
|
140
|
-
// Through a ref, and keyed on the client alone: keying on `execute` would re-subscribe every time
|
|
141
|
-
// `optionsJson` changed, and each re-subscribe takes a fresh baseline from the emission
|
|
142
|
-
// `onAuthStateChange` makes at registration. A sign-in landing in that window would be read as
|
|
143
|
-
// the baseline rather than as a change, and the query would never re-run.
|
|
154
|
+
/**
|
|
155
|
+
* Re-run when the signed-in identity changes. See `onIdentityChange` for which changes count.
|
|
156
|
+
*
|
|
157
|
+
* Through a ref, and keyed on the auth client alone: keying on `execute` would re-subscribe every
|
|
158
|
+
* time the options changed, and each re-subscribe takes a fresh baseline from the emission
|
|
159
|
+
* `onAuthStateChange` makes at registration. A sign-in landing in that window would be read as the
|
|
160
|
+
* baseline rather than as a change, and the query would never re-run.
|
|
161
|
+
*/
|
|
162
|
+
function useRerunOnIdentityChange(auth: AnyClient["auth"], execute: () => Promise<void>): void {
|
|
144
163
|
const executeRef = useRef(execute)
|
|
145
164
|
executeRef.current = execute
|
|
146
|
-
useEffect(() => onIdentityChange(
|
|
165
|
+
useEffect(() => onIdentityChange(auth, () => void executeRef.current()), [auth])
|
|
166
|
+
}
|
|
147
167
|
|
|
148
|
-
|
|
168
|
+
/**
|
|
169
|
+
* The read `options` describe. Through the untyped client: the generated row types do not survive
|
|
170
|
+
* a table name known only at run time, so the hook types the rows as `TRow` once they arrive.
|
|
171
|
+
*/
|
|
172
|
+
function readRows(client: AnyClient, table: string, options: UseQueryOptions | undefined) {
|
|
173
|
+
const source = client.from(table)
|
|
174
|
+
// A draft read is the same request against a different schema, so it branches here rather than
|
|
175
|
+
// duplicating every filter below.
|
|
176
|
+
let query = (options?.draft === true ? source.draft() : source).select(options?.select ?? "*")
|
|
177
|
+
for (const [col, val] of Object.entries(options?.filter ?? {})) {
|
|
178
|
+
query = query.eq(col, val)
|
|
179
|
+
}
|
|
180
|
+
if (options?.order !== undefined) {
|
|
181
|
+
query = query.order(options.order.column, { ascending: options.order.ascending ?? true })
|
|
182
|
+
}
|
|
183
|
+
query = withPage(query, options)
|
|
184
|
+
return options?.cache !== undefined ? query.cache(options.cache) : query
|
|
149
185
|
}
|
package/src/useSubscription.ts
CHANGED
|
@@ -22,6 +22,11 @@ export interface UseSubscriptionOptions<TRow> {
|
|
|
22
22
|
export interface UseSubscriptionResult {
|
|
23
23
|
/** Current subscription status. */
|
|
24
24
|
status: SubscriptionStatus
|
|
25
|
+
/**
|
|
26
|
+
* Why the server refused the subscription, such as a table that does not exist, while the status
|
|
27
|
+
* is CHANNEL_ERROR; null otherwise.
|
|
28
|
+
*/
|
|
29
|
+
error: Error | null
|
|
25
30
|
}
|
|
26
31
|
|
|
27
32
|
/**
|
|
@@ -41,7 +46,7 @@ export function useSubscription<TRow = Record<string, unknown>>(
|
|
|
41
46
|
opts: UseSubscriptionOptions<TRow>,
|
|
42
47
|
): UseSubscriptionResult {
|
|
43
48
|
const client = useSupatype()
|
|
44
|
-
const [
|
|
49
|
+
const [result, setResult] = useState<UseSubscriptionResult>({ status: "SUBSCRIBING", error: null })
|
|
45
50
|
|
|
46
51
|
// Stable ref so the effect doesn't re-run when the callback reference changes
|
|
47
52
|
const callbackRef = useRef(opts.callback)
|
|
@@ -60,7 +65,12 @@ export function useSubscription<TRow = Record<string, unknown>>(
|
|
|
60
65
|
},
|
|
61
66
|
(payload) => callbackRef.current(payload),
|
|
62
67
|
)
|
|
63
|
-
|
|
68
|
+
// The reason travels with the status it explains (N-FF5), so the two never disagree. The same
|
|
69
|
+
// answer keeps the same object, so React bails out of a render as it did for a bare status.
|
|
70
|
+
.subscribe((status, err) => {
|
|
71
|
+
const error = err ?? null
|
|
72
|
+
setResult((prev) => (prev.status === status && prev.error === error ? prev : { status, error }))
|
|
73
|
+
})
|
|
64
74
|
|
|
65
75
|
return () => {
|
|
66
76
|
channel.unsubscribe()
|
|
@@ -68,5 +78,5 @@ export function useSubscription<TRow = Record<string, unknown>>(
|
|
|
68
78
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
69
79
|
}, [client, channelName, opts.event, opts.schema, opts.table, opts.filter])
|
|
70
80
|
|
|
71
|
-
return
|
|
81
|
+
return result
|
|
72
82
|
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The functions a hook returns keep their identity across renders, as React's own hooks do, so an
|
|
3
|
+
* app can list them as effect dependencies.
|
|
4
|
+
*
|
|
5
|
+
* 0.9.1 release test (RB10): `useQuery` built a new `refetch` on every render, and the expo-auth
|
|
6
|
+
* example's `useEffect(() => { void refetch() }, [refetch])` looped, sending thousands of requests
|
|
7
|
+
* a second until React stopped it with "Maximum update depth exceeded".
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import React, { useEffect } from "react"
|
|
11
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
12
|
+
import { act, create, type ReactTestRenderer } from "react-test-renderer"
|
|
13
|
+
import { createClient, QueryBuilder, type AnyDatabase, type QueryResult } from "@supatype/client"
|
|
14
|
+
import { SupatypeProvider } from "../src/context.js"
|
|
15
|
+
import { useQuery, type UseQueryResult } from "../src/useQuery.js"
|
|
16
|
+
import { useAuth, type UseAuthReturn } from "../src/useAuth.js"
|
|
17
|
+
|
|
18
|
+
/** Every read answers at once with one row; returns how many were sent. */
|
|
19
|
+
function countedReads(): { count: () => number } {
|
|
20
|
+
let reads = 0
|
|
21
|
+
vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((onOk, onRejected) => {
|
|
22
|
+
reads += 1
|
|
23
|
+
return Promise.resolve<QueryResult<unknown[]>>({ data: [{ id: reads }], error: null, count: null }).then(onOk, onRejected)
|
|
24
|
+
})
|
|
25
|
+
return { count: () => reads }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const client = createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
|
|
29
|
+
|
|
30
|
+
/** Every `refetch` the hook handed out, one per render. */
|
|
31
|
+
const refetches: Array<UseQueryResult<unknown>["refetch"]> = []
|
|
32
|
+
|
|
33
|
+
function Posts({ id, label }: { id: number; label: string }): React.ReactElement {
|
|
34
|
+
const { data, refetch } = useQuery<AnyDatabase>("posts", { filter: { id } })
|
|
35
|
+
refetches.push(refetch)
|
|
36
|
+
return <p>{label}: {JSON.stringify(data)}</p>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Effect runs past this many stop refetching, so a loop ends instead of exhausting the heap. */
|
|
40
|
+
const EFFECT_CAP = 20
|
|
41
|
+
|
|
42
|
+
/** How many times `RefetchOnChange`'s effect has run. */
|
|
43
|
+
const effectRuns = { count: 0 }
|
|
44
|
+
|
|
45
|
+
/** The expo-auth pattern: refetch whenever `refetch` (or anything else listed) changes. */
|
|
46
|
+
function RefetchOnChange({ author }: { author: string }): React.ReactElement {
|
|
47
|
+
const { data, refetch } = useQuery<AnyDatabase>("profiles", { filter: { author } })
|
|
48
|
+
useEffect(() => {
|
|
49
|
+
effectRuns.count += 1
|
|
50
|
+
if (effectRuns.count <= EFFECT_CAP) refetch()
|
|
51
|
+
}, [author, refetch])
|
|
52
|
+
return <p>{JSON.stringify(data)}</p>
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function mount(element: React.ReactElement): Promise<ReactTestRenderer> {
|
|
56
|
+
let tree: ReactTestRenderer | null = null
|
|
57
|
+
await act(async () => {
|
|
58
|
+
tree = create(<SupatypeProvider client={client}>{element}</SupatypeProvider>)
|
|
59
|
+
})
|
|
60
|
+
if (tree === null) throw new Error("nothing rendered")
|
|
61
|
+
return tree
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
afterEach(() => {
|
|
65
|
+
vi.restoreAllMocks()
|
|
66
|
+
refetches.length = 0
|
|
67
|
+
effectRuns.count = 0
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
describe("useQuery's refetch", () => {
|
|
71
|
+
it("is the same function on every render while the query is unchanged", async () => {
|
|
72
|
+
countedReads()
|
|
73
|
+
const tree = await mount(<Posts id={1} label="first" />)
|
|
74
|
+
await act(async () => {
|
|
75
|
+
tree.update(<SupatypeProvider client={client}><Posts id={1} label="second" /></SupatypeProvider>)
|
|
76
|
+
})
|
|
77
|
+
expect(refetches.length).toBeGreaterThan(1)
|
|
78
|
+
expect(new Set(refetches).size).toBe(1)
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
it("is a new function once the query it runs changes", async () => {
|
|
82
|
+
countedReads()
|
|
83
|
+
const tree = await mount(<Posts id={1} label="posts" />)
|
|
84
|
+
const before = refetches.at(-1)
|
|
85
|
+
await act(async () => {
|
|
86
|
+
tree.update(<SupatypeProvider client={client}><Posts id={2} label="posts" /></SupatypeProvider>)
|
|
87
|
+
})
|
|
88
|
+
expect(refetches.at(-1)).not.toBe(before)
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
it("can be an effect dependency without the effect looping", async () => {
|
|
92
|
+
const reads = countedReads()
|
|
93
|
+
const errors = vi.spyOn(console, "error").mockImplementation(() => undefined)
|
|
94
|
+
await mount(<RefetchOnChange author="ada" />)
|
|
95
|
+
expect(effectRuns.count).toBe(1)
|
|
96
|
+
// One read from the hook on mount and one from the app's effect.
|
|
97
|
+
expect(reads.count()).toBe(2)
|
|
98
|
+
expect(errors).not.toHaveBeenCalled()
|
|
99
|
+
})
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
describe("useAuth's methods", () => {
|
|
103
|
+
it("are the same functions on every render", async () => {
|
|
104
|
+
vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 200 })))
|
|
105
|
+
const seen: UseAuthReturn[] = []
|
|
106
|
+
function Probe({ label }: { label: string }): React.ReactElement {
|
|
107
|
+
const auth = useAuth()
|
|
108
|
+
seen.push(auth)
|
|
109
|
+
return <p>{label}</p>
|
|
110
|
+
}
|
|
111
|
+
const tree = await mount(<Probe label="first" />)
|
|
112
|
+
await act(async () => {
|
|
113
|
+
tree.update(<SupatypeProvider client={client}><Probe label="second" /></SupatypeProvider>)
|
|
114
|
+
})
|
|
115
|
+
vi.unstubAllGlobals()
|
|
116
|
+
const first = seen[0]
|
|
117
|
+
const last = seen.at(-1)
|
|
118
|
+
if (first === undefined || last === undefined || first === last) throw new Error("expected two renders")
|
|
119
|
+
for (const name of ["signUp", "signIn", "signInWithOAuth", "signInWithSSO", "signInWithOtp", "signOut"] as const) {
|
|
120
|
+
expect(last[name], name).toBe(first[name])
|
|
121
|
+
}
|
|
122
|
+
})
|
|
123
|
+
})
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A request that throws instead of answering `{ data, error }` ends the hook's loading and becomes
|
|
3
|
+
* its `error`, reported once to the console.
|
|
4
|
+
*
|
|
5
|
+
* The client answers a refusal with `{ data, error }`, but some faults are thrown on purpose: a
|
|
6
|
+
* client with no API address or anon key throws from its first request. A hook that only awaited
|
|
7
|
+
* the request left the component on loading forever, with the rejection unhandled.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import React from "react"
|
|
11
|
+
import { afterEach, describe, expect, it, vi, type MockInstance } from "vitest"
|
|
12
|
+
import { act, create, type ReactTestRenderer } from "react-test-renderer"
|
|
13
|
+
import { MissingClientValuesError, createClient, MutationBuilder, QueryBuilder, type AnyDatabase, type SupatypeClient } from "@supatype/client"
|
|
14
|
+
import { SupatypeProvider } from "../src/context.js"
|
|
15
|
+
import { useQuery } from "../src/useQuery.js"
|
|
16
|
+
import { useMutation, type UseMutationResult } from "../src/useMutation.js"
|
|
17
|
+
import { useFunction, type UseFunctionResult } from "../src/useFunction.js"
|
|
18
|
+
import { useAuth } from "../src/useAuth.js"
|
|
19
|
+
|
|
20
|
+
/** The setup fault a client with no address throws: one of the SDK's errors, held as it is. */
|
|
21
|
+
class SetupFault extends MissingClientValuesError {
|
|
22
|
+
constructor() {
|
|
23
|
+
super("Supatype client has no API address", ["url"])
|
|
24
|
+
this.name = "SetupFault"
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function client(): SupatypeClient<AnyDatabase> {
|
|
29
|
+
return createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Every read through the client rejects with `thrown`, as a request that throws does. */
|
|
33
|
+
function readsThrow(thrown: unknown): void {
|
|
34
|
+
vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((_onOk, onRejected) =>
|
|
35
|
+
Promise.reject(thrown).then(undefined, onRejected),
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Every write through the client rejects with `thrown`. */
|
|
40
|
+
function writesThrow(thrown: unknown): void {
|
|
41
|
+
vi.spyOn(MutationBuilder.prototype, "then").mockImplementation((_onOk, onRejected) =>
|
|
42
|
+
Promise.reject(thrown).then(undefined, onRejected),
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The console.error calls that carry `thrown`. */
|
|
47
|
+
function reportsOf(logged: MockInstance<typeof console.error>, thrown: unknown): number {
|
|
48
|
+
return logged.mock.calls.filter((call) => call.includes(thrown)).length
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function silenceConsole(): MockInstance<typeof console.error> {
|
|
52
|
+
return vi.spyOn(console, "error").mockImplementation(() => undefined)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function Posts(): React.ReactElement {
|
|
56
|
+
const { data, error, loading } = useQuery<AnyDatabase>("posts")
|
|
57
|
+
if (loading) return <p>loading</p>
|
|
58
|
+
if (error !== null) return <p>error: {error.message}</p>
|
|
59
|
+
return <p>{data?.length ?? 0} rows</p>
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function render(element: React.ReactElement, using = client()): Promise<ReactTestRenderer> {
|
|
63
|
+
let tree: ReactTestRenderer | null = null
|
|
64
|
+
await act(async () => {
|
|
65
|
+
tree = create(<SupatypeProvider client={using}>{element}</SupatypeProvider>)
|
|
66
|
+
})
|
|
67
|
+
if (tree === null) throw new Error("nothing rendered")
|
|
68
|
+
return tree
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function textOf(tree: ReactTestRenderer): string {
|
|
72
|
+
return tree.root.findByType("p").children.join("")
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
afterEach(() => {
|
|
76
|
+
vi.restoreAllMocks()
|
|
77
|
+
vi.unstubAllGlobals()
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
describe("useQuery when the request throws", () => {
|
|
81
|
+
it("stops loading, renders the thrown error and reports it once", async () => {
|
|
82
|
+
const thrown = new SetupFault()
|
|
83
|
+
readsThrow(thrown)
|
|
84
|
+
const logged = silenceConsole()
|
|
85
|
+
const tree = await render(<Posts />)
|
|
86
|
+
expect(textOf(tree)).toBe("error: Supatype client has no API address")
|
|
87
|
+
expect(reportsOf(logged, thrown)).toBe(1)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it("still shows a returned error without reporting it", async () => {
|
|
91
|
+
vi.stubGlobal("fetch", vi.fn(async () => new Response(
|
|
92
|
+
JSON.stringify({ message: "permission denied", code: "42501" }),
|
|
93
|
+
{ status: 403, headers: { "Content-Type": "application/json" } },
|
|
94
|
+
)))
|
|
95
|
+
const logged = silenceConsole()
|
|
96
|
+
const tree = await render(<Posts />)
|
|
97
|
+
expect(textOf(tree)).toBe("error: permission denied")
|
|
98
|
+
expect(logged).not.toHaveBeenCalled()
|
|
99
|
+
})
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
describe("useMutation when the request throws", () => {
|
|
103
|
+
it("answers and holds the thrown error, stops loading and reports it once", async () => {
|
|
104
|
+
const thrown = new SetupFault()
|
|
105
|
+
writesThrow(thrown)
|
|
106
|
+
const logged = silenceConsole()
|
|
107
|
+
const probe: { hook: UseMutationResult<unknown> | null } = { hook: null }
|
|
108
|
+
function Probe(): null {
|
|
109
|
+
probe.hook = useMutation<AnyDatabase>("posts", "insert")
|
|
110
|
+
return null
|
|
111
|
+
}
|
|
112
|
+
await render(<Probe />)
|
|
113
|
+
let answer: Awaited<ReturnType<UseMutationResult<unknown>["mutate"]>> | null = null
|
|
114
|
+
await act(async () => {
|
|
115
|
+
answer = await probe.hook!.mutate({ title: "a" })
|
|
116
|
+
})
|
|
117
|
+
expect(answer).toEqual({ data: null, error: thrown, count: null })
|
|
118
|
+
expect(probe.hook!.error).toBe(thrown)
|
|
119
|
+
expect(probe.hook!.loading).toBe(false)
|
|
120
|
+
expect(reportsOf(logged, thrown)).toBe(1)
|
|
121
|
+
})
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
describe("useFunction when the request throws", () => {
|
|
125
|
+
it("answers and holds the thrown error, stops loading and reports it once", async () => {
|
|
126
|
+
const thrown = new SetupFault()
|
|
127
|
+
const using = client()
|
|
128
|
+
vi.spyOn(using.functions, "invoke").mockRejectedValue(thrown)
|
|
129
|
+
const logged = silenceConsole()
|
|
130
|
+
const probe: { hook: UseFunctionResult<unknown> | null } = { hook: null }
|
|
131
|
+
function Probe(): null {
|
|
132
|
+
probe.hook = useFunction("process-order")
|
|
133
|
+
return null
|
|
134
|
+
}
|
|
135
|
+
await render(<Probe />, using)
|
|
136
|
+
let answer: Awaited<ReturnType<UseFunctionResult<unknown>["invoke"]>> | null = null
|
|
137
|
+
await act(async () => {
|
|
138
|
+
answer = await probe.hook!.invoke({ id: 1 })
|
|
139
|
+
})
|
|
140
|
+
expect(answer).toEqual({ data: null, error: thrown })
|
|
141
|
+
expect(probe.hook!.error).toBe(thrown)
|
|
142
|
+
expect(probe.hook!.loading).toBe(false)
|
|
143
|
+
expect(reportsOf(logged, thrown)).toBe(1)
|
|
144
|
+
})
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
describe("useAuth when starting the client throws", () => {
|
|
148
|
+
it("stops loading, holds the thrown error and reports it once", async () => {
|
|
149
|
+
const thrown = new SetupFault()
|
|
150
|
+
const using = client()
|
|
151
|
+
vi.spyOn(using.auth, "initialize").mockRejectedValue(thrown)
|
|
152
|
+
const logged = silenceConsole()
|
|
153
|
+
const probe: { hook: ReturnType<typeof useAuth> | null } = { hook: null }
|
|
154
|
+
function Probe(): null {
|
|
155
|
+
probe.hook = useAuth()
|
|
156
|
+
return null
|
|
157
|
+
}
|
|
158
|
+
await render(<Probe />, using)
|
|
159
|
+
expect(probe.hook!.loading).toBe(false)
|
|
160
|
+
expect(probe.hook!.error).toBe(thrown)
|
|
161
|
+
expect(reportsOf(logged, thrown)).toBe(1)
|
|
162
|
+
})
|
|
163
|
+
})
|