@supatype/react 0.8.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.
@@ -3,19 +3,16 @@
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 } 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
 
10
- export interface MutationOptions {
11
- /** Simple equality filters for update/delete operations */
12
- filter?: Record<string, unknown> | undefined
13
- /**
14
- * For an update on a model that keeps drafts: publish the drafts it saves in the same call. Without
15
- * it the update saves a new draft of each record and the live rows stay as they are.
16
- */
17
- publish?: boolean | undefined
18
- }
10
+ /**
11
+ * `filter`: equality filters for an update or delete. `publish`: for an update on a model that keeps
12
+ * drafts, publish the drafts it saves in the same call. `select`: return the written rows, `true` for
13
+ * every column or the columns as `.select()` takes them; without it `data` is null.
14
+ */
15
+ export type MutationOptions = MutationRequest
19
16
 
20
17
  export interface UseMutationResult<TRow> {
21
18
  mutate(
@@ -32,7 +29,7 @@ export interface UseMutationResult<TRow> {
32
29
  * @example
33
30
  * ```tsx
34
31
  * const { mutate: createPost, loading } = useMutation('posts', 'insert')
35
- * await createPost({ title: 'Hello', status: 'draft' })
32
+ * const { data } = await createPost({ title: 'Hello', status: 'draft' }, { select: 'id' })
36
33
  *
37
34
  * const { mutate: editPost } = useMutation('posts', 'update')
38
35
  * await editPost({ title: 'Hello again' }, { filter: { id: postId }, publish: true })
@@ -61,12 +58,13 @@ export function useMutation<
61
58
  setLoading(true)
62
59
  setError(null)
63
60
  try {
64
- const publish = options?.publish
65
- const result = await runMutation<TRow>(client as AnyClient, table, operation, data, options?.filter, {
66
- ...(publish !== undefined && { publish }),
67
- })
61
+ const result = await runMutation<TRow>(client as AnyClient, table, operation, data, options)
68
62
  if (result.error !== null) setError(result.error)
69
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 }
70
68
  } finally {
71
69
  setLoading(false)
72
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 } 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 [data, setData] = useState<TRow[] | null>(null)
73
- const [error, setError] = useState<SupatypeError | null>(null)
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
- setLoading(false)
86
+ show({ loading: false })
84
87
  return
85
88
  }
86
- setLoading(true)
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
- // Through the untyped client: the generated row types do not survive a table name known only
89
- // at run time, so the rows are typed as `TRow` once they arrive.
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
- if (options?.filter !== undefined) {
98
- for (const [col, val] of Object.entries(options.filter)) {
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
- const result = await query
116
- setData(isRowsOf<TRow>(result.data) ? result.data : null)
117
- setError(result.error)
118
- setCount(result.count)
119
- setLoading(false)
120
- // eslint-disable-next-line react-hooks/exhaustive-deps
121
- }, [client, table, optionsJson])
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
- if (options?.refetchInterval !== undefined) {
127
- intervalRef.current = setInterval(() => void execute(), options.refetchInterval)
128
- }
129
- return () => {
130
- if (intervalRef.current !== null) {
131
- clearInterval(intervalRef.current)
132
- intervalRef.current = null
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(client.auth, () => void executeRef.current()), [client])
146
+ useEffect(() => onIdentityChange(auth, () => void executeRef.current()), [auth])
147
+ }
147
148
 
148
- return { data, error, count, loading, refetch: () => void execute() }
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
+ })
@@ -67,12 +67,25 @@ afterEach(() => {
67
67
  })
68
68
 
69
69
  describe("useMutation requests", () => {
70
- it("inserts the rows it is given and returns what the server answered", async () => {
70
+ it("inserts the rows it is given and asks for none back", async () => {
71
71
  const sent = stubFetch()
72
72
  const result = await mutateOnce("insert", [{ title: "a" }, { title: "b" }])
73
73
  expect(sent).toEqual([{ method: "POST", path: "/rest/v1/posts", body: [{ title: "a" }, { title: "b" }], profile: null, range: null }])
74
+ expect(result).toEqual({ data: null, error: null, count: null })
75
+ })
76
+
77
+ it("returns the rows the server answered when select names columns", async () => {
78
+ const sent = stubFetch()
79
+ const result = await mutateOnce("insert", { title: "a" }, { select: "id,title" })
80
+ expect(sent.map((r) => r.path)).toEqual(["/rest/v1/posts?select=id,title"])
81
+ expect(result).toEqual({ data: [{ id: 1 }], error: null, count: 1 })
82
+ })
83
+
84
+ it("returns every column with select: true", async () => {
85
+ const sent = stubFetch()
86
+ const result = await mutateOnce("update", { title: "b" }, { filter: { id: 7 }, select: true })
87
+ expect(sent.map((r) => r.path)).toEqual(["/rest/v1/posts?id=eq.7&select=*"])
74
88
  expect(result.data).toEqual([{ id: 1 }])
75
- expect(result.error).toBeNull()
76
89
  })
77
90
 
78
91
  it("upserts with the merge preference", async () => {
@@ -89,10 +102,18 @@ describe("useMutation requests", () => {
89
102
  ])
90
103
  })
91
104
 
92
- it("deletes only the rows the filter names, with no body", async () => {
105
+ it("deletes only the rows the filter names, with no body, and returns none", async () => {
93
106
  const sent = stubFetch()
94
- await mutateOnce("delete", undefined, { filter: { id: 7 } })
107
+ const result = await mutateOnce("delete", undefined, { filter: { id: 7 } })
95
108
  expect(sent).toEqual([{ method: "DELETE", path: "/rest/v1/posts?id=eq.7", body: null, profile: null, range: null }])
109
+ expect(result.data).toBeNull()
110
+ })
111
+
112
+ it("returns the deleted rows with select", async () => {
113
+ const sent = stubFetch()
114
+ const result = await mutateOnce("delete", undefined, { filter: { id: 7 }, select: "id" })
115
+ expect(sent.map((r) => r.path)).toEqual(["/rest/v1/posts?id=eq.7&select=id"])
116
+ expect(result.data).toEqual([{ id: 1 }])
96
117
  })
97
118
 
98
119
  // Each used to go out as a request the server could only refuse: a POST or PATCH with no body,
@@ -107,7 +128,8 @@ describe("useMutation requests", () => {
107
128
  const sent = stubFetch()
108
129
  const result = await mutateOnce(operation, data)
109
130
  expect(sent).toEqual([])
110
- 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)
111
133
  })
112
134
  })
113
135
 
@@ -169,11 +191,11 @@ describe("useMutation update on a model that keeps drafts", () => {
169
191
 
170
192
  it("saves a draft of each matched record and returns the drafts, leaving the live row alone", async () => {
171
193
  const sent = stubDraftsServer()
172
- const result = await mutateOnce("update", { title: "b" }, { filter: { id: ID } })
194
+ const result = await mutateOnce("update", { title: "b" }, { filter: { id: ID }, select: true })
173
195
  expect(sent.map((r) => `${r.method} ${r.path}`)).toEqual([
174
196
  `GET /rest/v1/posts?id=eq.${ID}&select=id`,
175
197
  "POST /rest/v1/rpc/save_drafts",
176
- `GET /rest/v1/posts?id=in.(${ID})`,
198
+ `GET /rest/v1/posts?select=*&id=in.(${ID})`,
177
199
  ])
178
200
  expect(sent[1]!.body).toEqual({ model_table: "posts", record_ids: [ID], data: { title: "b" }, publish: false })
179
201
  expect(sent[2]!.profile).toBe("draft")
@@ -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
+ })