@supatype/react 0.3.5 → 0.7.0
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 +19 -0
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/RichText.d.ts +9 -6
- package/dist/RichText.d.ts.map +1 -1
- package/dist/RichText.js +27 -10
- package/dist/RichText.js.map +1 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +2 -1
- package/dist/context.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/live-preview-message.d.ts +19 -0
- package/dist/live-preview-message.d.ts.map +1 -0
- package/dist/live-preview-message.js +45 -0
- package/dist/live-preview-message.js.map +1 -0
- package/dist/useAuth.d.ts +7 -2
- package/dist/useAuth.d.ts.map +1 -1
- package/dist/useAuth.js +15 -10
- package/dist/useAuth.js.map +1 -1
- package/dist/useFunction.d.ts.map +1 -1
- package/dist/useFunction.js +15 -9
- package/dist/useFunction.js.map +1 -1
- package/dist/useLivePreview.d.ts +12 -1
- package/dist/useLivePreview.d.ts.map +1 -1
- package/dist/useLivePreview.js +18 -12
- package/dist/useLivePreview.js.map +1 -1
- package/dist/useMutation.d.ts +11 -6
- package/dist/useMutation.d.ts.map +1 -1
- package/dist/useMutation.js +14 -30
- package/dist/useMutation.js.map +1 -1
- package/dist/useQuery.d.ts.map +1 -1
- package/dist/useQuery.js +5 -6
- package/dist/useQuery.js.map +1 -1
- package/package.json +10 -5
- package/src/RichText.tsx +32 -19
- package/src/context.tsx +3 -2
- package/src/index.ts +1 -0
- package/src/live-preview-message.ts +52 -0
- package/src/useAuth.ts +21 -12
- package/src/useFunction.ts +13 -9
- package/src/useLivePreview.ts +26 -13
- package/src/useMutation.ts +21 -34
- package/src/useQuery.ts +8 -9
- package/tests/RichText.test.tsx +77 -0
- package/tests/tsconfig.json +9 -0
- package/tests/useAuth-redirect.test.tsx +89 -0
- package/tests/useAuth-signup.test.tsx +61 -0
- package/tests/useLivePreview-origin.test.tsx +108 -0
- package/tests/useMutation-requests.test.tsx +188 -0
- package/tests/useSubscription-status.test.tsx +48 -0
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"noEmit": true,
|
|
5
|
+
"composite": false,
|
|
6
|
+
"rootDir": "../.."
|
|
7
|
+
},
|
|
8
|
+
"include": ["../../../ts-reset.d.ts", "./**/*.ts", "./**/*.tsx", "../src/**/*.ts", "../src/**/*.tsx", "../../client/tests/helpers/*.ts"]
|
|
9
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An OAuth sign-in finishes on the page the auth server returns to, with nothing in the app.
|
|
3
|
+
*
|
|
4
|
+
* The server sends the browser back with the session in the URL. `SupatypeProvider` and `useAuth`
|
|
5
|
+
* have to show that user (and a refusal) once the client has read it, or the round trip lands on a
|
|
6
|
+
* signed-out page with tokens in the address bar.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import React from "react"
|
|
10
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
11
|
+
import { act, create, type ReactTestRenderer } from "react-test-renderer"
|
|
12
|
+
import { createClient } from "@supatype/client"
|
|
13
|
+
import { SupatypeProvider } from "../src/context.js"
|
|
14
|
+
import { useAuth } from "../src/useAuth.js"
|
|
15
|
+
|
|
16
|
+
const RAW_USER = {
|
|
17
|
+
id: "user-1",
|
|
18
|
+
email: "ada@example.com",
|
|
19
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
20
|
+
updated_at: "2024-01-01T00:00:00Z",
|
|
21
|
+
app_metadata: { provider: "github" },
|
|
22
|
+
user_metadata: { full_name: "Ada Lovelace" },
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function accessToken(): string {
|
|
26
|
+
const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString("base64url")
|
|
27
|
+
return `eyJhbGciOiJub25lIn0.${payload}.sig`
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function stubBrowser(href: string): ReturnType<typeof vi.fn> {
|
|
31
|
+
const store = new Map<string, string>([["supatype.auth.session-oauth-provider", "github"]])
|
|
32
|
+
const replaceState = vi.fn()
|
|
33
|
+
vi.stubGlobal("window", {
|
|
34
|
+
location: { href, protocol: "https:" },
|
|
35
|
+
history: { state: null, replaceState },
|
|
36
|
+
localStorage: {
|
|
37
|
+
getItem: (k: string) => store.get(k) ?? null,
|
|
38
|
+
setItem: (k: string, v: string) => { store.set(k, v) },
|
|
39
|
+
removeItem: (k: string) => { store.delete(k) },
|
|
40
|
+
},
|
|
41
|
+
})
|
|
42
|
+
return replaceState
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function Probe(): React.ReactElement {
|
|
46
|
+
const { user, loading, error } = useAuth()
|
|
47
|
+
const text = loading ? "loading" : user?.email ?? `signed out${error ? `: ${error.message} (${error.provider ?? "?"})` : ""}`
|
|
48
|
+
return <p>{text}</p>
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function renderApp(): Promise<ReactTestRenderer> {
|
|
52
|
+
const client = createClient({ url: "http://localhost:9999", anonKey: "anon" })
|
|
53
|
+
let renderer: ReactTestRenderer | null = null
|
|
54
|
+
await act(async () => {
|
|
55
|
+
renderer = create(<SupatypeProvider client={client}><Probe /></SupatypeProvider>)
|
|
56
|
+
await client.auth.getSession()
|
|
57
|
+
})
|
|
58
|
+
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) })
|
|
59
|
+
return renderer!
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function shown(renderer: ReactTestRenderer): string {
|
|
63
|
+
return renderer.root.findByType("p").children.join("")
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
afterEach(() => {
|
|
67
|
+
vi.unstubAllGlobals()
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
describe("useAuth after an OAuth redirect", () => {
|
|
71
|
+
it("shows the user the URL signed in, and cleans the URL", async () => {
|
|
72
|
+
const replaceState = stubBrowser(`https://app.example/#access_token=${accessToken()}&refresh_token=rt-1&sb=`)
|
|
73
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify(RAW_USER), { status: 200 })))
|
|
74
|
+
|
|
75
|
+
const renderer = await renderApp()
|
|
76
|
+
|
|
77
|
+
expect(shown(renderer)).toBe("ada@example.com")
|
|
78
|
+
expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/")
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
it("exposes a refusal the server reported in the URL", async () => {
|
|
82
|
+
stubBrowser("https://app.example/?error=server_error&error_description=Error+getting+user+profile#error=server_error&error_description=Error+getting+user+profile&sb=")
|
|
83
|
+
vi.stubGlobal("fetch", vi.fn())
|
|
84
|
+
|
|
85
|
+
const renderer = await renderApp()
|
|
86
|
+
|
|
87
|
+
expect(shown(renderer)).toBe("signed out: Error getting user profile (github)")
|
|
88
|
+
})
|
|
89
|
+
})
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A sign-up that waits for email confirmation leaves `useAuth` signed out.
|
|
3
|
+
*
|
|
4
|
+
* The auth server answers it with the bare user and no tokens. Treating that as a session showed
|
|
5
|
+
* apps a blank signed-in user (id "") that survived a reload.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import React from "react"
|
|
9
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
10
|
+
import { act, create, type ReactTestRenderer } from "react-test-renderer"
|
|
11
|
+
import { createClient } from "@supatype/client"
|
|
12
|
+
import { SupatypeProvider } from "../src/context.js"
|
|
13
|
+
import { useAuth, type UseAuthReturn } from "../src/useAuth.js"
|
|
14
|
+
|
|
15
|
+
const PENDING_USER = {
|
|
16
|
+
id: "user-pending",
|
|
17
|
+
email: "ada@example.com",
|
|
18
|
+
confirmation_sent_at: "2024-01-01T00:00:00Z",
|
|
19
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
20
|
+
updated_at: "2024-01-01T00:00:00Z",
|
|
21
|
+
app_metadata: { provider: "email" },
|
|
22
|
+
user_metadata: {},
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const probe: { auth: UseAuthReturn | null } = { auth: null }
|
|
26
|
+
|
|
27
|
+
function Probe(): React.ReactElement {
|
|
28
|
+
const auth = useAuth()
|
|
29
|
+
probe.auth = auth
|
|
30
|
+
return <p>{auth.loading ? "loading" : auth.user === null ? "signed out" : `signed in as "${auth.user.id}"`}</p>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function renderApp(): Promise<ReactTestRenderer> {
|
|
34
|
+
const client = createClient({ url: "http://localhost:9999", anonKey: "anon" })
|
|
35
|
+
let renderer: ReactTestRenderer | null = null
|
|
36
|
+
await act(async () => {
|
|
37
|
+
renderer = create(<SupatypeProvider client={client}><Probe /></SupatypeProvider>)
|
|
38
|
+
await client.auth.getSession()
|
|
39
|
+
})
|
|
40
|
+
return renderer!
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
afterEach(() => {
|
|
44
|
+
vi.unstubAllGlobals()
|
|
45
|
+
probe.auth = null
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
describe("useAuth after a sign-up waiting for email confirmation", () => {
|
|
49
|
+
it("stays signed out and returns no session", async () => {
|
|
50
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify(PENDING_USER), { status: 200 })))
|
|
51
|
+
const renderer = await renderApp()
|
|
52
|
+
|
|
53
|
+
let session: unknown = "unset"
|
|
54
|
+
await act(async () => {
|
|
55
|
+
session = (await probe.auth!.signUp({ email: "ada@example.com", password: "secret-pass" })).data.session
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
expect(session).toBeNull()
|
|
59
|
+
expect(renderer.root.findByType("p").children.join("")).toBe("signed out")
|
|
60
|
+
})
|
|
61
|
+
})
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `useLivePreview` applies a preview message only when Studio sent it.
|
|
3
|
+
*
|
|
4
|
+
* The hook used to apply any `supatype:live-preview` message posted to the window, whoever posted
|
|
5
|
+
* it. Any page that could frame the app, or any window it opened, could repaint it with content of
|
|
6
|
+
* its choosing. A message now has to come from the parent window and from Studio's origin: the
|
|
7
|
+
* origin of the provider's client URL (Studio is served at `/studio/` on it) unless `studioOrigin`
|
|
8
|
+
* names another.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import React from "react"
|
|
12
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
|
|
13
|
+
import { act, create, type ReactTestRenderer } from "react-test-renderer"
|
|
14
|
+
import { createClient } from "@supatype/client"
|
|
15
|
+
import { SupatypeProvider } from "../src/context.js"
|
|
16
|
+
import { useLivePreview, type UseLivePreviewOptions } from "../src/useLivePreview.js"
|
|
17
|
+
|
|
18
|
+
interface Post {
|
|
19
|
+
title: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const API_URL = "http://localhost:18473"
|
|
23
|
+
const studioWindow = new EventTarget()
|
|
24
|
+
|
|
25
|
+
let renderer: ReactTestRenderer | null = null
|
|
26
|
+
let latest: { data: Post; isPreview: boolean } | null = null
|
|
27
|
+
|
|
28
|
+
function Probe({ opts }: { opts: UseLivePreviewOptions<Post> }): null {
|
|
29
|
+
latest = useLivePreview(opts)
|
|
30
|
+
return null
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function mount(opts: UseLivePreviewOptions<Post>, withProvider = true): void {
|
|
34
|
+
const probe = <Probe opts={opts} />
|
|
35
|
+
const client = createClient({ url: API_URL, anonKey: "anon" })
|
|
36
|
+
act(() => {
|
|
37
|
+
renderer = create(withProvider ? <SupatypeProvider client={client}>{probe}</SupatypeProvider> : probe)
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A `message` event as a browser delivers one. Node's `MessageEvent` refuses a window as `source`. */
|
|
42
|
+
function post(origin: string, source: EventTarget = studioWindow): void {
|
|
43
|
+
const event = Object.assign(new Event("message"), {
|
|
44
|
+
origin,
|
|
45
|
+
source,
|
|
46
|
+
data: { type: "supatype:live-preview", model: "post", data: { title: "Edited" } },
|
|
47
|
+
})
|
|
48
|
+
act(() => {
|
|
49
|
+
window.dispatchEvent(event)
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const initialData: Post = { title: "Saved" }
|
|
54
|
+
|
|
55
|
+
beforeEach(() => {
|
|
56
|
+
vi.stubGlobal("window", Object.assign(new EventTarget(), { parent: studioWindow }))
|
|
57
|
+
vi.spyOn(console, "warn").mockImplementation(() => undefined)
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
afterEach(() => {
|
|
61
|
+
act(() => renderer?.unmount())
|
|
62
|
+
renderer = null
|
|
63
|
+
latest = null
|
|
64
|
+
vi.unstubAllGlobals()
|
|
65
|
+
vi.restoreAllMocks()
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
describe("useLivePreview origin check", () => {
|
|
69
|
+
it("applies a message from the client URL's origin", () => {
|
|
70
|
+
mount({ initialData, model: "post" })
|
|
71
|
+
post(API_URL)
|
|
72
|
+
expect(latest).toEqual({ data: { title: "Edited" }, isPreview: true })
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it("ignores a message from a foreign origin", () => {
|
|
76
|
+
mount({ initialData, model: "post" })
|
|
77
|
+
post("https://attacker.example")
|
|
78
|
+
expect(latest).toEqual({ data: initialData, isPreview: false })
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
it("ignores a message from the right origin sent by a window that is not the parent", () => {
|
|
82
|
+
mount({ initialData, model: "post" })
|
|
83
|
+
post(API_URL, new EventTarget())
|
|
84
|
+
expect(latest).toEqual({ data: initialData, isPreview: false })
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it("trusts only the origins `studioOrigin` names when it is given", () => {
|
|
88
|
+
mount({ initialData, model: "post", studioOrigin: ["https://studio.example.com/studio/"] })
|
|
89
|
+
post(API_URL)
|
|
90
|
+
expect(latest?.isPreview).toBe(false)
|
|
91
|
+
post("https://studio.example.com")
|
|
92
|
+
expect(latest).toEqual({ data: { title: "Edited" }, isPreview: true })
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it("ignores every message with no provider and no `studioOrigin`", () => {
|
|
96
|
+
mount({ initialData, model: "post" }, false)
|
|
97
|
+
post(API_URL)
|
|
98
|
+
expect(latest).toEqual({ data: initialData, isPreview: false })
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
it("says once which origin it refused, so a misconfigured Studio origin is findable", () => {
|
|
102
|
+
mount({ initialData, model: "post" })
|
|
103
|
+
post("https://attacker.example")
|
|
104
|
+
post("https://attacker.example")
|
|
105
|
+
expect(console.warn).toHaveBeenCalledTimes(1)
|
|
106
|
+
expect(vi.mocked(console.warn).mock.calls[0]?.[0]).toContain("https://attacker.example")
|
|
107
|
+
})
|
|
108
|
+
})
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What `useMutation` and `useQuery` send for a table named at run time.
|
|
3
|
+
*
|
|
4
|
+
* Both reach the table through the untyped client, because the generated row types do not survive
|
|
5
|
+
* a dynamic table name. These pin the requests that come out, so typing that path cannot quietly
|
|
6
|
+
* change a method, a filter or a body.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import React from "react"
|
|
10
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
|
|
11
|
+
import { act, create } from "react-test-renderer"
|
|
12
|
+
import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase } from "@supatype/client"
|
|
13
|
+
import { SupatypeProvider } from "../src/context.js"
|
|
14
|
+
import { useMutation, type MutationOperation, type UseMutationResult } from "../src/useMutation.js"
|
|
15
|
+
import { useQuery, type UseQueryOptions } from "../src/useQuery.js"
|
|
16
|
+
|
|
17
|
+
interface SentRequest {
|
|
18
|
+
method: string
|
|
19
|
+
path: string
|
|
20
|
+
body: unknown
|
|
21
|
+
profile: string | null
|
|
22
|
+
range: string | null
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function stubFetch(): SentRequest[] {
|
|
26
|
+
const sent: SentRequest[] = []
|
|
27
|
+
vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
|
|
28
|
+
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url)
|
|
29
|
+
const headers = new Headers(init?.headers)
|
|
30
|
+
sent.push({
|
|
31
|
+
method: init?.method ?? "GET",
|
|
32
|
+
path: decodeURIComponent(url.pathname + url.search),
|
|
33
|
+
body: typeof init?.body === "string" ? JSON.parse(init.body) : init?.body ?? null,
|
|
34
|
+
profile: headers.get("Accept-Profile"),
|
|
35
|
+
range: headers.get("Range"),
|
|
36
|
+
})
|
|
37
|
+
return new Response(JSON.stringify([{ id: 1 }]), { status: 200, headers: { "Content-Type": "application/json" } })
|
|
38
|
+
}))
|
|
39
|
+
return sent
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function client(): ReturnType<typeof createClient<AnyDatabase>> {
|
|
43
|
+
return createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function mutateOnce(
|
|
47
|
+
operation: MutationOperation,
|
|
48
|
+
...args: Parameters<UseMutationResult<unknown>["mutate"]>
|
|
49
|
+
): Promise<Awaited<ReturnType<UseMutationResult<unknown>["mutate"]>>> {
|
|
50
|
+
const probe: { mutation: UseMutationResult<unknown> | null } = { mutation: null }
|
|
51
|
+
function Probe(): null {
|
|
52
|
+
probe.mutation = useMutation<AnyDatabase>("posts", operation)
|
|
53
|
+
return null
|
|
54
|
+
}
|
|
55
|
+
await act(async () => {
|
|
56
|
+
create(<SupatypeProvider client={client()}><Probe /></SupatypeProvider>)
|
|
57
|
+
})
|
|
58
|
+
let result: Awaited<ReturnType<UseMutationResult<unknown>["mutate"]>> | null = null
|
|
59
|
+
await act(async () => {
|
|
60
|
+
result = await probe.mutation!.mutate(...args)
|
|
61
|
+
})
|
|
62
|
+
return result!
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
afterEach(() => {
|
|
66
|
+
vi.unstubAllGlobals()
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
describe("useMutation requests", () => {
|
|
70
|
+
it("inserts the rows it is given and returns what the server answered", async () => {
|
|
71
|
+
const sent = stubFetch()
|
|
72
|
+
const result = await mutateOnce("insert", [{ title: "a" }, { title: "b" }])
|
|
73
|
+
expect(sent).toEqual([{ method: "POST", path: "/rest/v1/posts", body: [{ title: "a" }, { title: "b" }], profile: null, range: null }])
|
|
74
|
+
expect(result.data).toEqual([{ id: 1 }])
|
|
75
|
+
expect(result.error).toBeNull()
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it("upserts with the merge preference", async () => {
|
|
79
|
+
const sent = stubFetch()
|
|
80
|
+
await mutateOnce("upsert", { id: 1, title: "a" })
|
|
81
|
+
expect(sent).toEqual([{ method: "POST", path: "/rest/v1/posts", body: { id: 1, title: "a" }, profile: null, range: null }])
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
it("updates only the rows the filter names", async () => {
|
|
85
|
+
const sent = stubFetch()
|
|
86
|
+
await mutateOnce("update", { title: "b" }, { filter: { id: 7, status: "draft" } })
|
|
87
|
+
expect(sent).toEqual([
|
|
88
|
+
{ method: "PATCH", path: "/rest/v1/posts?id=eq.7&status=eq.draft", body: { title: "b" }, profile: null, range: null },
|
|
89
|
+
])
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it("deletes only the rows the filter names, with no body", async () => {
|
|
93
|
+
const sent = stubFetch()
|
|
94
|
+
await mutateOnce("delete", undefined, { filter: { id: 7 } })
|
|
95
|
+
expect(sent).toEqual([{ method: "DELETE", path: "/rest/v1/posts?id=eq.7", body: null, profile: null, range: null }])
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
// Each used to go out as a request the server could only refuse: a POST or PATCH with no body,
|
|
99
|
+
// or a PATCH whose body was a list.
|
|
100
|
+
const refusals: Array<[string, MutationOperation, Parameters<UseMutationResult<unknown>["mutate"]>[0], string]> = [
|
|
101
|
+
["an insert with nothing to write", "insert", undefined, "insert needs the row or rows to write"],
|
|
102
|
+
["an upsert with nothing to write", "upsert", undefined, "upsert needs the row or rows to write"],
|
|
103
|
+
["an update with no changes", "update", undefined, "update needs one object of the changes to make"],
|
|
104
|
+
["an update given a list", "update", [{ title: "a" }], "update needs one object of the changes to make"],
|
|
105
|
+
]
|
|
106
|
+
it.each(refusals)("refuses %s without a request", async (_label, operation, data, message) => {
|
|
107
|
+
const sent = stubFetch()
|
|
108
|
+
const result = await mutateOnce(operation, data)
|
|
109
|
+
expect(sent).toEqual([])
|
|
110
|
+
expect(result).toEqual({ data: null, error: { message }, count: null })
|
|
111
|
+
})
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
describe("useQuery requests", () => {
|
|
115
|
+
async function queryOnce(options: UseQueryOptions): Promise<SentRequest[]> {
|
|
116
|
+
const sent = stubFetch()
|
|
117
|
+
function Probe(): null {
|
|
118
|
+
useQuery<AnyDatabase>("posts", options)
|
|
119
|
+
return null
|
|
120
|
+
}
|
|
121
|
+
await act(async () => {
|
|
122
|
+
create(<SupatypeProvider client={client()}><Probe /></SupatypeProvider>)
|
|
123
|
+
})
|
|
124
|
+
return sent
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
it("applies every option to one GET", async () => {
|
|
128
|
+
const sent = await queryOnce({
|
|
129
|
+
select: "id,title",
|
|
130
|
+
filter: { status: "published" },
|
|
131
|
+
order: { column: "created_at", ascending: false },
|
|
132
|
+
limit: 10,
|
|
133
|
+
offset: 20,
|
|
134
|
+
})
|
|
135
|
+
expect(sent).toHaveLength(1)
|
|
136
|
+
expect(sent[0]!.method).toBe("GET")
|
|
137
|
+
expect(sent[0]!.path).toBe(
|
|
138
|
+
"/rest/v1/posts?select=id,title&status=eq.published&order=created_at.desc.nullslast&limit=10",
|
|
139
|
+
)
|
|
140
|
+
expect(sent[0]!.profile).toBeNull()
|
|
141
|
+
expect(sent[0]!.range).toBe("20-29")
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
it("reads the draft schema when asked", async () => {
|
|
145
|
+
const sent = await queryOnce({ draft: true })
|
|
146
|
+
expect(sent[0]!.path).toBe("/rest/v1/posts?select=*")
|
|
147
|
+
expect(sent[0]!.profile).toBe("draft")
|
|
148
|
+
})
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
describe("useMutation update on a model that keeps drafts", () => {
|
|
152
|
+
const ID = "7b1f115e-418d-4e92-91d0-f199ebd06e5e"
|
|
153
|
+
|
|
154
|
+
/** Answers as the database does: the matched keys, `save_drafts`' answer, then the draft rows. */
|
|
155
|
+
function stubDraftsServer(): SentRequest[] {
|
|
156
|
+
const sent = stubFetch()
|
|
157
|
+
const answers = [[{ id: ID }], [{ record_id: ID, version: 2, status: "draft" }], [{ id: ID, title: "b" }]]
|
|
158
|
+
vi.mocked(fetch).mockImplementation(async (input, init) => {
|
|
159
|
+
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url)
|
|
160
|
+
const body = typeof init?.body === "string" ? JSON.parse(init.body) : null
|
|
161
|
+
sent.push({ method: init?.method ?? "GET", path: decodeURIComponent(url.pathname + url.search), body, profile: new Headers(init?.headers).get("Accept-Profile"), range: null })
|
|
162
|
+
return new Response(JSON.stringify(answers[sent.length - 1] ?? []), { status: 200, headers: { "Content-Type": "application/json" } })
|
|
163
|
+
})
|
|
164
|
+
return sent
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
beforeEach(() => registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } }))
|
|
168
|
+
afterEach(() => forgetRegisteredDraftModels())
|
|
169
|
+
|
|
170
|
+
it("saves a draft of each matched record and returns the drafts, leaving the live row alone", async () => {
|
|
171
|
+
const sent = stubDraftsServer()
|
|
172
|
+
const result = await mutateOnce("update", { title: "b" }, { filter: { id: ID } })
|
|
173
|
+
expect(sent.map((r) => `${r.method} ${r.path}`)).toEqual([
|
|
174
|
+
`GET /rest/v1/posts?id=eq.${ID}&select=id`,
|
|
175
|
+
"POST /rest/v1/rpc/save_drafts",
|
|
176
|
+
`GET /rest/v1/posts?id=in.(${ID})`,
|
|
177
|
+
])
|
|
178
|
+
expect(sent[1]!.body).toEqual({ model_table: "posts", record_ids: [ID], data: { title: "b" }, publish: false })
|
|
179
|
+
expect(sent[2]!.profile).toBe("draft")
|
|
180
|
+
expect(result).toEqual({ data: [{ id: ID, title: "b" }], error: null, count: 1 })
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
it("publishes in the same call when asked", async () => {
|
|
184
|
+
const sent = stubDraftsServer()
|
|
185
|
+
await mutateOnce("update", { title: "b" }, { filter: { id: ID }, publish: true })
|
|
186
|
+
expect(sent[1]!.body).toEqual({ model_table: "posts", record_ids: [ID], data: { title: "b" }, publish: true })
|
|
187
|
+
})
|
|
188
|
+
})
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `useSubscription`'s status follows the realtime socket swap that signing in causes.
|
|
3
|
+
*
|
|
4
|
+
* The hook passes the channel's own status through, so it was only as right as the client: the
|
|
5
|
+
* swap reported nothing, and the hook read SUBSCRIBED from the moment the anon socket joined until
|
|
6
|
+
* well after the signed-in socket had joined. An insert made in that window never arrived.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import React from "react"
|
|
10
|
+
import { vi } from "vitest"
|
|
11
|
+
import { act, create, type ReactTestRenderer } from "react-test-renderer"
|
|
12
|
+
import { describeStatusAcrossSignIn, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
|
|
13
|
+
|
|
14
|
+
const shared = vi.hoisted(() => ({ harness: null as SocketSwapHarness | null }))
|
|
15
|
+
|
|
16
|
+
vi.mock("../src/context.js", () => ({
|
|
17
|
+
useSupatype: () => ({ realtime: shared.harness?.realtime }),
|
|
18
|
+
}))
|
|
19
|
+
|
|
20
|
+
import { useSubscription, type SubscriptionStatus } from "../src/useSubscription.js"
|
|
21
|
+
|
|
22
|
+
let renderer: ReactTestRenderer | null = null
|
|
23
|
+
let latest: SubscriptionStatus | null = null
|
|
24
|
+
|
|
25
|
+
function Probe(): null {
|
|
26
|
+
latest = useSubscription("public:task", { table: "task", callback: () => undefined }).status
|
|
27
|
+
return null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
describeStatusAcrossSignIn(
|
|
31
|
+
"useSubscription",
|
|
32
|
+
(harness) => {
|
|
33
|
+
shared.harness = harness
|
|
34
|
+
act(() => {
|
|
35
|
+
renderer = create(<Probe />)
|
|
36
|
+
})
|
|
37
|
+
return { status: () => latest ?? "unrendered" }
|
|
38
|
+
},
|
|
39
|
+
() => {
|
|
40
|
+
act(() => renderer?.unmount())
|
|
41
|
+
renderer = null
|
|
42
|
+
latest = null
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
swap: ["SUBSCRIBING", "SUBSCRIBED", "SUBSCRIBING", "SUBSCRIBED"],
|
|
46
|
+
refused: ["SUBSCRIBING", "SUBSCRIBED", "SUBSCRIBING", "CHANNEL_ERROR"],
|
|
47
|
+
},
|
|
48
|
+
)
|