@supatype/react 0.9.0 → 0.9.1
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 +14 -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 +9 -0
- 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.map +1 -1
- package/dist/useQuery.js +71 -55
- package/dist/useQuery.js.map +1 -1
- package/package.json +3 -3
- package/src/useAuth.ts +22 -1
- package/src/useFunction.ts +6 -1
- package/src/useMutation.ts +5 -1
- package/src/useQuery.ts +82 -60
- package/tests/thrown-errors.test.tsx +163 -0
- package/tests/useAuth-sso.test.tsx +67 -0
- package/tests/useMutation-requests.test.tsx +2 -1
- package/tests/useQuery-race.test.tsx +98 -0
- package/tsconfig.tsbuildinfo +1 -1
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 } from "@supatype/client/bindings"
|
|
8
8
|
|
|
9
9
|
export interface UseQueryOptions {
|
|
10
10
|
/** PostgREST select expression (default: '*') */
|
|
@@ -69,81 +69,103 @@ 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: true })
|
|
73
|
+
const latest = useRef(0)
|
|
76
74
|
|
|
77
75
|
// Stable reference to options for the effect dep
|
|
78
76
|
const optionsJson = JSON.stringify(options)
|
|
79
|
-
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
|
80
77
|
|
|
81
78
|
const execute = useCallback(async () => {
|
|
79
|
+
const request = ++latest.current
|
|
80
|
+
// Only the latest request is shown: an older one that lands after it is dropped, whatever it
|
|
81
|
+
// brought, so it cannot replace newer rows or an error the newer request did not have.
|
|
82
|
+
const show = (next: Partial<RowsState<TRow>>): void => {
|
|
83
|
+
if (request === latest.current) setState((current) => ({ ...current, ...next }))
|
|
84
|
+
}
|
|
82
85
|
if (options?.enabled === false) {
|
|
83
|
-
|
|
86
|
+
show({ loading: false })
|
|
84
87
|
return
|
|
85
88
|
}
|
|
86
|
-
|
|
89
|
+
show({ loading: true })
|
|
90
|
+
show(await settledRows<TRow>(client as AnyClient, table, options))
|
|
91
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
92
|
+
}, [client, table, optionsJson])
|
|
87
93
|
|
|
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
|
-
)
|
|
94
|
+
useRunAndRefetch(execute, options?.refetchInterval)
|
|
95
|
+
useRerunOnIdentityChange(client.auth, execute)
|
|
96
96
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
query = query.eq(col, val)
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
if (options?.order !== undefined) {
|
|
103
|
-
query = query.order(options.order.column, { ascending: options.order.ascending ?? true })
|
|
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
|
-
}
|
|
97
|
+
return { ...state, refetch: () => void execute() }
|
|
98
|
+
}
|
|
114
99
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
100
|
+
/** What the hook shows: the latest request's answer, and whether one is in flight. */
|
|
101
|
+
interface RowsState<TRow> {
|
|
102
|
+
data: TRow[] | null
|
|
103
|
+
error: SupatypeError | null
|
|
104
|
+
count: number | null
|
|
105
|
+
loading: boolean
|
|
106
|
+
}
|
|
122
107
|
|
|
108
|
+
/**
|
|
109
|
+
* The read's answer as the hook shows it. A request that throws (a client with no API address, say)
|
|
110
|
+
* ends like one that was refused, and is reported even when a newer request has replaced it.
|
|
111
|
+
*/
|
|
112
|
+
async function settledRows<TRow>(
|
|
113
|
+
client: AnyClient,
|
|
114
|
+
table: string,
|
|
115
|
+
options: UseQueryOptions | undefined,
|
|
116
|
+
): Promise<RowsState<TRow>> {
|
|
117
|
+
try {
|
|
118
|
+
const result = await readRows(client, table, options)
|
|
119
|
+
return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error, count: result.count, loading: false }
|
|
120
|
+
} catch (e) {
|
|
121
|
+
return { data: null, error: reportThrown(`useQuery("${table}")`, e), count: null, loading: false }
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Run `execute` now and whenever it changes, and every `interval` milliseconds when one is set. */
|
|
126
|
+
function useRunAndRefetch(execute: () => Promise<void>, interval: number | undefined): void {
|
|
123
127
|
useEffect(() => {
|
|
124
128
|
void execute()
|
|
129
|
+
if (interval === undefined) return undefined
|
|
130
|
+
const timer = setInterval(() => void execute(), interval)
|
|
131
|
+
return () => clearInterval(timer)
|
|
132
|
+
}, [execute, interval])
|
|
133
|
+
}
|
|
125
134
|
|
|
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.
|
|
135
|
+
/**
|
|
136
|
+
* Re-run when the signed-in identity changes. See `onIdentityChange` for which changes count.
|
|
137
|
+
*
|
|
138
|
+
* Through a ref, and keyed on the auth client alone: keying on `execute` would re-subscribe every
|
|
139
|
+
* time the options changed, and each re-subscribe takes a fresh baseline from the emission
|
|
140
|
+
* `onAuthStateChange` makes at registration. A sign-in landing in that window would be read as the
|
|
141
|
+
* baseline rather than as a change, and the query would never re-run.
|
|
142
|
+
*/
|
|
143
|
+
function useRerunOnIdentityChange(auth: AnyClient["auth"], execute: () => Promise<void>): void {
|
|
144
144
|
const executeRef = useRef(execute)
|
|
145
145
|
executeRef.current = execute
|
|
146
|
-
useEffect(() => onIdentityChange(
|
|
146
|
+
useEffect(() => onIdentityChange(auth, () => void executeRef.current()), [auth])
|
|
147
|
+
}
|
|
147
148
|
|
|
148
|
-
|
|
149
|
+
/**
|
|
150
|
+
* The read `options` describe. Through the untyped client: the generated row types do not survive
|
|
151
|
+
* a table name known only at run time, so the hook types the rows as `TRow` once they arrive.
|
|
152
|
+
*/
|
|
153
|
+
function readRows(client: AnyClient, table: string, options: UseQueryOptions | undefined) {
|
|
154
|
+
const source = client.from(table)
|
|
155
|
+
// A draft read is the same request against a different schema, so it branches here rather than
|
|
156
|
+
// duplicating every filter below.
|
|
157
|
+
let query = (options?.draft === true ? source.draft() : source).select(options?.select ?? "*")
|
|
158
|
+
for (const [col, val] of Object.entries(options?.filter ?? {})) {
|
|
159
|
+
query = query.eq(col, val)
|
|
160
|
+
}
|
|
161
|
+
if (options?.order !== undefined) {
|
|
162
|
+
query = query.order(options.order.column, { ascending: options.order.ascending ?? true })
|
|
163
|
+
}
|
|
164
|
+
if (options?.limit !== undefined) {
|
|
165
|
+
query = query.limit(options.limit)
|
|
166
|
+
}
|
|
167
|
+
if (options?.offset !== undefined && options.limit !== undefined) {
|
|
168
|
+
query = query.range(options.offset, options.offset + options.limit - 1)
|
|
169
|
+
}
|
|
170
|
+
return options?.cache !== undefined ? query.cache(options.cache) : query
|
|
149
171
|
}
|
|
@@ -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
|
+
})
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `useAuth().signInWithSSO`: SAML single sign-on from a component, beside `signInWithOAuth`. It is
|
|
3
|
+
* the client's own `signInWithSSO`, so what the auth server receives is asserted here.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import React from "react"
|
|
7
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
8
|
+
import { act, create } from "react-test-renderer"
|
|
9
|
+
import { createClient, PKCE_METHOD_S256 } from "@supatype/client"
|
|
10
|
+
import { SupatypeProvider } from "../src/context.js"
|
|
11
|
+
import { useAuth, type UseAuthReturn } from "../src/useAuth.js"
|
|
12
|
+
|
|
13
|
+
const IDP_URL = "https://idp.example/sso?SAMLRequest=abc"
|
|
14
|
+
const PROVIDER_ID = "8a6f1f4e-2b1c-4f5e-9d3a-6b7c8d9e0f1a"
|
|
15
|
+
|
|
16
|
+
const probe: { auth: UseAuthReturn | null } = { auth: null }
|
|
17
|
+
|
|
18
|
+
function Probe(): React.ReactElement {
|
|
19
|
+
probe.auth = useAuth()
|
|
20
|
+
return <p />
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Render a provider over a real client and record the requests it sends. */
|
|
24
|
+
async function renderApp(): Promise<Array<{ url: string; body: unknown }>> {
|
|
25
|
+
const sent: Array<{ url: string; body: unknown }> = []
|
|
26
|
+
vi.stubGlobal("fetch", vi.fn(async (input: string, init?: RequestInit) => {
|
|
27
|
+
sent.push({ url: input, body: typeof init?.body === "string" ? JSON.parse(init.body) as unknown : null })
|
|
28
|
+
return new Response(JSON.stringify({ url: IDP_URL }), { status: 200 })
|
|
29
|
+
}))
|
|
30
|
+
const client = createClient({ url: "http://localhost:9999", anonKey: "anon" })
|
|
31
|
+
await act(async () => {
|
|
32
|
+
create(<SupatypeProvider client={client}><Probe /></SupatypeProvider>)
|
|
33
|
+
await client.auth.getSession()
|
|
34
|
+
})
|
|
35
|
+
return sent
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
afterEach(() => {
|
|
39
|
+
vi.unstubAllGlobals()
|
|
40
|
+
probe.auth = null
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
describe("useAuth().signInWithSSO", () => {
|
|
44
|
+
it("starts SSO for an email domain and returns the identity provider's URL", async () => {
|
|
45
|
+
const sent = await renderApp()
|
|
46
|
+
const result = await probe.auth!.signInWithSSO({ domain: "acme.com", options: { skipBrowserRedirect: true } })
|
|
47
|
+
|
|
48
|
+
expect(result).toEqual({ data: { url: IDP_URL }, error: null })
|
|
49
|
+
const sso = sent.find((r) => r.url === "http://localhost:9999/auth/v1/sso")
|
|
50
|
+
expect(sso?.body).toMatchObject({ domain: "acme.com", skip_http_redirect: true, code_challenge_method: PKCE_METHOD_S256 })
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it("starts SSO for a provider named by its ID", async () => {
|
|
54
|
+
const sent = await renderApp()
|
|
55
|
+
await probe.auth!.signInWithSSO({ providerId: PROVIDER_ID, options: { skipBrowserRedirect: true } })
|
|
56
|
+
|
|
57
|
+
expect(sent.find((r) => r.url.endsWith("/auth/v1/sso"))?.body).toMatchObject({ provider_id: PROVIDER_ID })
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it("takes a domain or a provider ID, never both", async () => {
|
|
61
|
+
await renderApp()
|
|
62
|
+
const both = (): unknown =>
|
|
63
|
+
// @ts-expect-error: one of domain or providerId, never both
|
|
64
|
+
probe.auth!.signInWithSSO({ domain: "acme.com", providerId: PROVIDER_ID })
|
|
65
|
+
expect(typeof both).toBe("function")
|
|
66
|
+
})
|
|
67
|
+
})
|
|
@@ -128,7 +128,8 @@ describe("useMutation requests", () => {
|
|
|
128
128
|
const sent = stubFetch()
|
|
129
129
|
const result = await mutateOnce(operation, data)
|
|
130
130
|
expect(sent).toEqual([])
|
|
131
|
-
expect(result).toEqual({ data: null, error: { message }, count: null })
|
|
131
|
+
expect({ ...result, error: { ...result.error } }).toEqual({ data: null, error: { message }, count: null })
|
|
132
|
+
expect(result.error).toBeInstanceOf(Error)
|
|
132
133
|
})
|
|
133
134
|
})
|
|
134
135
|
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `useQuery` shows the answer to the latest request. When the options change while a read is in
|
|
3
|
+
* flight, the older read can finish last; whatever it brings, rows, a returned error or a throw,
|
|
4
|
+
* must not replace what the newer one showed.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import React from "react"
|
|
8
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
9
|
+
import { act, create, type ReactTestRenderer } from "react-test-renderer"
|
|
10
|
+
import { createClient, QueryBuilder, SupatypeError, type AnyDatabase, type QueryResult } from "@supatype/client"
|
|
11
|
+
import { SupatypeProvider } from "../src/context.js"
|
|
12
|
+
import { useQuery } from "../src/useQuery.js"
|
|
13
|
+
|
|
14
|
+
interface PendingRead {
|
|
15
|
+
resolve(result: QueryResult<unknown[]>): void
|
|
16
|
+
reject(reason: unknown): void
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Every read waits until the test settles it, in the order the hook sent them. */
|
|
20
|
+
function heldReads(): PendingRead[] {
|
|
21
|
+
const reads: PendingRead[] = []
|
|
22
|
+
vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((onOk, onRejected) => {
|
|
23
|
+
const answer = new Promise<QueryResult<unknown[]>>((resolve, reject) => reads.push({ resolve, reject }))
|
|
24
|
+
return answer.then(onOk, onRejected)
|
|
25
|
+
})
|
|
26
|
+
return reads
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function rows(id: number): QueryResult<unknown[]> {
|
|
30
|
+
return { data: [{ id }], error: null, count: null }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function Posts({ id }: { id: number }): React.ReactElement {
|
|
34
|
+
const { data, error, loading } = useQuery<AnyDatabase>("posts", { filter: { id } })
|
|
35
|
+
if (loading) return <p>loading</p>
|
|
36
|
+
if (error !== null) return <p>error: {error.message}</p>
|
|
37
|
+
return <p>rows: {JSON.stringify(data)}</p>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const client = createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
|
|
41
|
+
|
|
42
|
+
/** Renders for id 1, then id 2, leaving both reads held. */
|
|
43
|
+
async function twoReadsInFlight(): Promise<{ tree: ReactTestRenderer; older: PendingRead; newer: PendingRead }> {
|
|
44
|
+
const reads = heldReads()
|
|
45
|
+
let tree: ReactTestRenderer | null = null
|
|
46
|
+
await act(async () => {
|
|
47
|
+
tree = create(<SupatypeProvider client={client}><Posts id={1} /></SupatypeProvider>)
|
|
48
|
+
})
|
|
49
|
+
if (tree === null) throw new Error("nothing rendered")
|
|
50
|
+
const rendered: ReactTestRenderer = tree
|
|
51
|
+
const older = reads.at(-1)
|
|
52
|
+
await act(async () => {
|
|
53
|
+
rendered.update(<SupatypeProvider client={client}><Posts id={2} /></SupatypeProvider>)
|
|
54
|
+
})
|
|
55
|
+
const newer = reads.at(-1)
|
|
56
|
+
if (older === undefined || newer === undefined || older === newer) throw new Error("expected two reads")
|
|
57
|
+
return { tree: rendered, older, newer }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function textOf(tree: ReactTestRenderer): string {
|
|
61
|
+
return tree.root.findByType("p").children.join("")
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
afterEach(() => {
|
|
65
|
+
vi.restoreAllMocks()
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
describe("useQuery when an older read finishes last", () => {
|
|
69
|
+
it("keeps the newer rows over the older rows", async () => {
|
|
70
|
+
const { tree, older, newer } = await twoReadsInFlight()
|
|
71
|
+
await act(async () => newer.resolve(rows(2)))
|
|
72
|
+
await act(async () => older.resolve(rows(1)))
|
|
73
|
+
expect(textOf(tree)).toBe('rows: [{"id":2}]')
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it("keeps the newer rows over the older read's returned error", async () => {
|
|
77
|
+
const { tree, older, newer } = await twoReadsInFlight()
|
|
78
|
+
await act(async () => newer.resolve(rows(2)))
|
|
79
|
+
await act(async () => older.resolve({ data: null, error: new SupatypeError({ message: "permission denied" }), count: null }))
|
|
80
|
+
expect(textOf(tree)).toBe('rows: [{"id":2}]')
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
it("keeps the newer rows over the older read's throw, still reporting it", async () => {
|
|
84
|
+
const logged = vi.spyOn(console, "error").mockImplementation(() => undefined)
|
|
85
|
+
const thrown = new Error("Supatype client has no API address")
|
|
86
|
+
const { tree, older, newer } = await twoReadsInFlight()
|
|
87
|
+
await act(async () => newer.resolve(rows(2)))
|
|
88
|
+
await act(async () => older.reject(thrown))
|
|
89
|
+
expect(textOf(tree)).toBe('rows: [{"id":2}]')
|
|
90
|
+
expect(logged.mock.calls.filter((call) => call.includes(thrown))).toHaveLength(1)
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
it("stays loading while the newer read is in flight after the older one lands", async () => {
|
|
94
|
+
const { tree, older } = await twoReadsInFlight()
|
|
95
|
+
await act(async () => older.resolve(rows(1)))
|
|
96
|
+
expect(textOf(tree)).toBe("loading")
|
|
97
|
+
})
|
|
98
|
+
})
|