@supatype/client 0.3.6 → 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 +58 -31
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/auth-redirect.d.ts +48 -0
- package/dist/auth-redirect.d.ts.map +1 -0
- package/dist/auth-redirect.js +70 -0
- package/dist/auth-redirect.js.map +1 -0
- package/dist/auth.d.ts +78 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +373 -274
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +16 -0
- package/dist/bindings.d.ts.map +1 -0
- package/dist/bindings.js +13 -0
- package/dist/bindings.js.map +1 -0
- package/dist/caller-types.d.ts +18 -0
- package/dist/caller-types.d.ts.map +1 -0
- package/dist/caller-types.js +22 -0
- package/dist/caller-types.js.map +1 -0
- package/dist/draft-create.d.ts +12 -0
- package/dist/draft-create.d.ts.map +1 -0
- package/dist/draft-create.js +47 -0
- package/dist/draft-create.js.map +1 -0
- package/dist/draft-models-registry.d.ts +27 -0
- package/dist/draft-models-registry.d.ts.map +1 -0
- package/dist/draft-models-registry.js +61 -0
- package/dist/draft-models-registry.js.map +1 -0
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +42 -34
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +102 -60
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -28
- package/dist/errors.js.map +1 -1
- package/dist/exact-response.d.ts.map +1 -1
- package/dist/exact-response.js +2 -1
- package/dist/exact-response.js.map +1 -1
- package/dist/exact-values.d.ts +2 -0
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +12 -10
- package/dist/exact-values.js.map +1 -1
- package/dist/fetch-with-retry.d.ts +21 -6
- package/dist/fetch-with-retry.d.ts.map +1 -1
- package/dist/fetch-with-retry.js +67 -53
- package/dist/fetch-with-retry.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +11 -3
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +10 -6
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/filters.d.ts +51 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +117 -0
- package/dist/filters.js.map +1 -0
- package/dist/generated-client.d.ts +7 -0
- package/dist/generated-client.d.ts.map +1 -0
- package/dist/generated-client.js +7 -0
- package/dist/generated-client.js.map +1 -0
- package/dist/graphql-document.d.ts +39 -0
- package/dist/graphql-document.d.ts.map +1 -0
- package/dist/graphql-document.js +228 -0
- package/dist/graphql-document.js.map +1 -0
- package/dist/graphql-json.d.ts +56 -0
- package/dist/graphql-json.d.ts.map +1 -0
- package/dist/graphql-json.js +220 -0
- package/dist/graphql-json.js.map +1 -0
- package/dist/graphql-transport.d.ts +28 -0
- package/dist/graphql-transport.d.ts.map +1 -0
- package/dist/graphql-transport.js +77 -0
- package/dist/graphql-transport.js.map +1 -0
- package/dist/index.d.ts +103 -40
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +153 -157
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +61 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +83 -0
- package/dist/json.js.map +1 -0
- package/dist/jwt.d.ts +16 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +37 -0
- package/dist/jwt.js.map +1 -0
- package/dist/live-preview.d.ts +23 -0
- package/dist/live-preview.d.ts.map +1 -0
- package/dist/live-preview.js +28 -0
- package/dist/live-preview.js.map +1 -0
- package/dist/mutation-request.d.ts +17 -0
- package/dist/mutation-request.d.ts.map +1 -0
- package/dist/mutation-request.js +41 -0
- package/dist/mutation-request.js.map +1 -0
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +8 -6
- package/dist/preview.js.map +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +19 -13
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +108 -29
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +294 -224
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +20 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +105 -12
- package/dist/realtime.js.map +1 -1
- package/dist/select-types.d.ts +99 -0
- package/dist/select-types.d.ts.map +1 -0
- package/dist/select-types.js +2 -0
- package/dist/select-types.js.map +1 -0
- package/dist/storage.d.ts +81 -11
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +129 -37
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +69 -0
- package/dist/table-subscription.d.ts.map +1 -0
- package/dist/table-subscription.js +93 -0
- package/dist/table-subscription.js.map +1 -0
- package/dist/types.d.ts +84 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth-redirect.ts +90 -0
- package/src/auth.ts +421 -280
- package/src/bindings.ts +22 -0
- package/src/caller-types.ts +27 -0
- package/src/draft-create.ts +51 -0
- package/src/draft-models-registry.ts +81 -0
- package/src/error-codes-doc.ts +44 -35
- package/src/errors.ts +72 -28
- package/src/exact-response.ts +2 -1
- package/src/exact-values.ts +16 -9
- package/src/fetch-with-retry.ts +80 -70
- package/src/field-kinds-registry.ts +22 -9
- package/src/filters.ts +133 -0
- package/src/generated-client.ts +6 -0
- package/src/graphql-document.ts +234 -0
- package/src/graphql-json.ts +243 -0
- package/src/graphql-transport.ts +97 -0
- package/src/index.ts +272 -201
- package/src/json.ts +117 -0
- package/src/jwt.ts +37 -0
- package/src/live-preview.ts +37 -0
- package/src/mutation-request.ts +66 -0
- package/src/preview.ts +9 -11
- package/src/query-cache.ts +19 -16
- package/src/query.ts +389 -270
- package/src/realtime.ts +116 -13
- package/src/select-types.ts +184 -0
- package/src/storage.ts +214 -43
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +90 -5
- package/tests/auth-error-codes.test.ts +53 -0
- package/tests/auth-errors.test.ts +84 -0
- package/tests/auth-events.test.ts +136 -0
- package/tests/auth-url-session.test.ts +204 -0
- package/tests/auth.test.ts +122 -26
- package/tests/count.test.ts +60 -0
- package/tests/data-plane-auth.test.ts +21 -46
- package/tests/draft-insert.integration.test.ts +118 -0
- package/tests/draft-insert.test.ts +225 -0
- package/tests/draft-profile.test.ts +55 -84
- package/tests/draft-update.integration.test.ts +122 -0
- package/tests/draft-update.test.ts +174 -0
- package/tests/dynamic-headers.test.ts +45 -0
- package/tests/entry-points.test.ts +42 -0
- package/tests/exact-response.test.ts +4 -4
- package/tests/exact-values.test.ts +14 -25
- package/tests/field-kinds-registry.test.ts +3 -3
- package/tests/filters.test.ts +146 -0
- package/tests/graphql-json.test.ts +199 -0
- package/tests/helpers/mock-websocket.ts +44 -11
- package/tests/helpers/oauth-binding.ts +92 -0
- package/tests/helpers/signup-binding.ts +73 -0
- package/tests/helpers/socket-swap.ts +139 -0
- package/tests/mfa-totp-integration.test.ts +13 -20
- package/tests/postgrest-error-codes.test.ts +85 -0
- package/tests/query-cache.test.ts +116 -117
- package/tests/query.test.ts +29 -31
- package/tests/rate-limit-integration.test.ts +4 -12
- package/tests/realtime-exact-values.test.ts +2 -4
- package/tests/realtime-presence.test.ts +75 -0
- package/tests/realtime-session-auth.test.ts +2 -4
- package/tests/realtime-swap-status.test.ts +62 -0
- package/tests/retry-integration.test.ts +3 -8
- package/tests/retry-policy.test.ts +166 -0
- package/tests/rpc-resend.test.ts +24 -0
- package/tests/server-bodies.test.ts +139 -0
- package/tests/serverless.test.ts +2 -2
- package/tests/signed-url-absolute.test.ts +2 -5
- package/tests/storage-object-shape.test.ts +101 -0
- package/tests/storage-quota-integration.test.ts +3 -2
- package/tests/storage-reference-url.test.ts +51 -0
- package/tests/storage-upload-browser.test.ts +71 -0
- package/tests/storage-upload-limit-integration.test.ts +12 -22
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +13 -13
- package/tests/table-subscription.test.ts +105 -0
- package/tests/table-transport.test.ts +94 -0
- package/tests/tsconfig.json +1 -1
- package/tests/types.test.ts +153 -1
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest"
|
|
2
|
+
import { getErrorDocumentation } from "../src/error-codes-doc.js"
|
|
3
|
+
import { PostgrestErrorCodes } from "../src/errors.js"
|
|
4
|
+
import { MutationBuilder, QueryBuilder } from "../src/query.js"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The codes PostgREST 14 answers with, recorded from a live `postgrest/postgrest:v14.18` against
|
|
8
|
+
* Postgres 17, and the constant a caller would compare each one with.
|
|
9
|
+
*
|
|
10
|
+
* Two of these moved in PostgREST 13: an expired token is `PGRST303` (it was `PGRST301`), and a
|
|
11
|
+
* missing table is `PGRST205` (it was the SQLSTATE `42P01`). A database error is passed through
|
|
12
|
+
* under its SQLSTATE, with no `PGRST` prefix, so a constant spelled `PGRST23505` never matched a
|
|
13
|
+
* unique violation in any release.
|
|
14
|
+
*/
|
|
15
|
+
const RECORDED: Array<{ case: string; status: number; code: string; constant: string }> = [
|
|
16
|
+
{ case: "expired JWT", status: 401, code: "PGRST303", constant: PostgrestErrorCodes.JWT_EXPIRED },
|
|
17
|
+
{ case: "JWT with a bad signature", status: 401, code: "PGRST301", constant: PostgrestErrorCodes.JWT_INVALID },
|
|
18
|
+
{ case: "missing table", status: 404, code: "PGRST205", constant: PostgrestErrorCodes.UNDEFINED_TABLE },
|
|
19
|
+
{ case: "insert into an unknown column", status: 400, code: "PGRST204", constant: PostgrestErrorCodes.SCHEMA_CACHE_MISS },
|
|
20
|
+
{ case: "single() with no rows", status: 406, code: "PGRST116", constant: PostgrestErrorCodes.NOT_FOUND },
|
|
21
|
+
{ case: "row-level security denial, signed in", status: 403, code: "42501", constant: PostgrestErrorCodes.PERMISSION_DENIED },
|
|
22
|
+
{ case: "foreign key violation", status: 409, code: "23503", constant: PostgrestErrorCodes.FK_VIOLATION },
|
|
23
|
+
{ case: "unique violation", status: 409, code: "23505", constant: PostgrestErrorCodes.UNIQUE_VIOLATION },
|
|
24
|
+
{ case: "not-null violation", status: 400, code: "23502", constant: PostgrestErrorCodes.NOT_NULL_VIOLATION },
|
|
25
|
+
{ case: "check violation", status: 400, code: "23514", constant: PostgrestErrorCodes.CHECK_VIOLATION },
|
|
26
|
+
{ case: "invalid input syntax", status: 400, code: "22P02", constant: PostgrestErrorCodes.INVALID_INPUT },
|
|
27
|
+
{ case: "filter on an unknown column", status: 400, code: "42703", constant: PostgrestErrorCodes.UNDEFINED_COLUMN },
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
/** PostgREST 14's message for a `vnd.pgrst.object+json` request that did not find one row. */
|
|
31
|
+
const SINGLE_ROW_MESSAGE = "Cannot coerce the result to a single JSON object"
|
|
32
|
+
|
|
33
|
+
describe("PostgREST error codes", () => {
|
|
34
|
+
it.each(RECORDED)("$case: the constant is the code PostgREST answers", ({ code, constant }) => {
|
|
35
|
+
expect(constant).toBe(code)
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it.each(RECORDED)("$case: the documentation has an entry for the code", ({ code, status }) => {
|
|
39
|
+
const entry = getErrorDocumentation(code)
|
|
40
|
+
expect(entry?.category).toBe("postgrest")
|
|
41
|
+
expect(entry?.httpStatus).toBe(status)
|
|
42
|
+
})
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
describe("single() without exactly one row", () => {
|
|
46
|
+
const emptyArray = (): Response =>
|
|
47
|
+
new Response("[]", { status: 200, headers: { "Content-Type": "application/json" } })
|
|
48
|
+
|
|
49
|
+
it("a read words it as PostgREST does", async () => {
|
|
50
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
|
|
51
|
+
const { error } = await new QueryBuilder("http://x", "/rest/v1/t", {}).single()
|
|
52
|
+
vi.unstubAllGlobals()
|
|
53
|
+
expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it("a write words it as PostgREST does", async () => {
|
|
57
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
|
|
58
|
+
const { error } = await new MutationBuilder("http://x", "/rest/v1/t", {}, "PATCH", {}).single()
|
|
59
|
+
vi.unstubAllGlobals()
|
|
60
|
+
expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
describe("a field validator's refusal", () => {
|
|
65
|
+
// Recorded from the kitchen-sink stack: what the gateway answers when `validate-chat-body` refuses.
|
|
66
|
+
const refused = (): Response =>
|
|
67
|
+
new Response(
|
|
68
|
+
JSON.stringify({ field: "body", message: "That reads as shouting.", error: "That reads as shouting." }),
|
|
69
|
+
{ status: 422, headers: { "Content-Type": "application/json" } },
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
it("keeps the field on a read", async () => {
|
|
73
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(refused()))
|
|
74
|
+
const { error } = await new QueryBuilder("http://x", "/rest/v1/t", {})
|
|
75
|
+
vi.unstubAllGlobals()
|
|
76
|
+
expect(error).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it("keeps the field on a write, which is where a validator runs", async () => {
|
|
80
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(refused()))
|
|
81
|
+
const { error } = await new MutationBuilder("http://x", "/rest/v1/t", { body: "HELLO" }, "POST", {})
|
|
82
|
+
vi.unstubAllGlobals()
|
|
83
|
+
expect(error).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
|
|
84
|
+
})
|
|
85
|
+
})
|
|
@@ -1,118 +1,117 @@
|
|
|
1
|
-
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"
|
|
2
|
-
import { QueryBuilder } from "../src/query.js"
|
|
3
|
-
import { QueryCache, buildCacheKey, identityFingerprint } from "../src/query-cache.js"
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
cache
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
})
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
"
|
|
67
|
-
|
|
68
|
-
"
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
//
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
expect(
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
expect(r2.
|
|
85
|
-
expect(
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
"
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
expect(
|
|
104
|
-
})
|
|
105
|
-
|
|
106
|
-
it("sends public directive when server and public", async () => {
|
|
107
|
-
fetchMock.mockResolvedValue(
|
|
108
|
-
new Response(JSON.stringify([]), { status: 200, headers: { "Content-Type": "application/json" } }),
|
|
109
|
-
)
|
|
110
|
-
|
|
111
|
-
await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
|
|
112
|
-
.cache({ ttl: 30_000, server: true, public: true })
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
})
|
|
1
|
+
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"
|
|
2
|
+
import { QueryBuilder } from "../src/query.js"
|
|
3
|
+
import { QueryCache, buildCacheKey, identityFingerprint } from "../src/query-cache.js"
|
|
4
|
+
import { fetchCall, fetchCalls, header, mockFetch } from "./support/fetch-mock.js"
|
|
5
|
+
|
|
6
|
+
describe("query-cache", () => {
|
|
7
|
+
it("identityFingerprint differs for different subs", () => {
|
|
8
|
+
const payloadA = btoa(JSON.stringify({ sub: "a", role: "authenticated" }))
|
|
9
|
+
const payloadB = btoa(JSON.stringify({ sub: "b", role: "authenticated" }))
|
|
10
|
+
const a = identityFingerprint({ Authorization: `Bearer x.${payloadA}.y` }, "user")
|
|
11
|
+
const b = identityFingerprint({ Authorization: `Bearer x.${payloadB}.y` }, "user")
|
|
12
|
+
expect(a).not.toBe(b)
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
it("identityFingerprint stable for same sub across token strings", () => {
|
|
16
|
+
const payload = btoa(JSON.stringify({ sub: "user-1", role: "authenticated" }))
|
|
17
|
+
const a = identityFingerprint({ Authorization: `Bearer aaa.${payload}.sig1` }, "user")
|
|
18
|
+
const b = identityFingerprint({ Authorization: `Bearer bbb.${payload}.sig2` }, "user")
|
|
19
|
+
expect(a).toBe(b)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it("public scope uses global fingerprint", () => {
|
|
23
|
+
expect(identityFingerprint({ Authorization: "Bearer x" }, "public")).toBe("global")
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it("buildCacheKey is stable", () => {
|
|
27
|
+
const h = { Authorization: "Bearer x" }
|
|
28
|
+
const k1 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
|
|
29
|
+
const k2 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
|
|
30
|
+
expect(k1).toBe(k2)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it("QueryCache expires entries", () => {
|
|
34
|
+
vi.useFakeTimers()
|
|
35
|
+
const cache = new QueryCache()
|
|
36
|
+
cache.set("k", { data: [{ id: 1 }], error: null, count: 1 }, 1000)
|
|
37
|
+
expect(cache.get("k")?.data).toEqual([{ id: 1 }])
|
|
38
|
+
vi.advanceTimersByTime(1001)
|
|
39
|
+
expect(cache.get("k")).toBeNull()
|
|
40
|
+
vi.useRealTimers()
|
|
41
|
+
})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
describe("QueryBuilder.cache", () => {
|
|
45
|
+
const fetchMock = mockFetch()
|
|
46
|
+
|
|
47
|
+
beforeEach(() => {
|
|
48
|
+
fetchMock.mockReset()
|
|
49
|
+
vi.stubGlobal("fetch", fetchMock)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
afterEach(() => {
|
|
53
|
+
vi.unstubAllGlobals()
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it("returns cached result without second fetch", async () => {
|
|
57
|
+
fetchMock.mockResolvedValue(
|
|
58
|
+
new Response(JSON.stringify([{ id: 1 }]), {
|
|
59
|
+
status: 200,
|
|
60
|
+
headers: { "Content-Type": "application/json" },
|
|
61
|
+
}),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
const cache = new QueryCache()
|
|
65
|
+
const qb = new QueryBuilder<{ id: number }>(
|
|
66
|
+
"http://localhost:9999",
|
|
67
|
+
"/rest/v1/posts",
|
|
68
|
+
{ Authorization: "Bearer anon" },
|
|
69
|
+
"*",
|
|
70
|
+
cache,
|
|
71
|
+
).cache({ ttl: 60_000 })
|
|
72
|
+
|
|
73
|
+
// Counted per table URL rather than across every request, because the client also fetches the
|
|
74
|
+
// project's column types once so it can keep bigInt, decimal and money columns exact. That
|
|
75
|
+
// request is cached per project and is not what this test is about.
|
|
76
|
+
const tableCalls = (): number =>
|
|
77
|
+
fetchCalls(fetchMock).filter(({ url }) => url.includes("/rest/v1/posts")).length
|
|
78
|
+
|
|
79
|
+
const r1 = await qb
|
|
80
|
+
expect(r1.data).toEqual([{ id: 1 }])
|
|
81
|
+
expect(tableCalls()).toBe(1)
|
|
82
|
+
|
|
83
|
+
const r2 = await qb
|
|
84
|
+
expect(r2.data).toEqual([{ id: 1 }])
|
|
85
|
+
expect(r2.meta?.cacheStatus).toBe("HIT")
|
|
86
|
+
expect(tableCalls()).toBe(1)
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it("sends X-Supatype-Cache when server: true", async () => {
|
|
90
|
+
fetchMock.mockResolvedValue(
|
|
91
|
+
new Response(JSON.stringify([]), {
|
|
92
|
+
status: 200,
|
|
93
|
+
headers: {
|
|
94
|
+
"Content-Type": "application/json",
|
|
95
|
+
"X-Supatype-Cache-Status": "MISS",
|
|
96
|
+
},
|
|
97
|
+
}),
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
|
|
101
|
+
.cache({ ttl: 30_000, server: true })
|
|
102
|
+
|
|
103
|
+
expect(header(fetchCall(fetchMock).init, "X-Supatype-Cache")).toBe("max-age=30")
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it("sends public directive when server and public", async () => {
|
|
107
|
+
fetchMock.mockResolvedValue(
|
|
108
|
+
new Response(JSON.stringify([]), { status: 200, headers: { "Content-Type": "application/json" } }),
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
|
|
112
|
+
.cache({ ttl: 30_000, server: true, public: true })
|
|
113
|
+
|
|
114
|
+
expect(header(fetchCall(fetchMock).init, "X-Supatype-Cache")).toBe("max-age=30, public")
|
|
115
|
+
})
|
|
116
|
+
})
|
|
118
117
|
|
package/tests/query.test.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
2
|
import { QueryBuilder, MutationBuilder, defaultQueryCache } from "../src/query.js"
|
|
3
|
+
import { fetchCall, fetchReturning, header, type FetchMock } from "./support/fetch-mock.js"
|
|
3
4
|
|
|
4
5
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
5
6
|
|
|
@@ -12,25 +13,17 @@ interface Post { id: string; title: string; status: string }
|
|
|
12
13
|
function mockFetch(
|
|
13
14
|
body: unknown,
|
|
14
15
|
opts: { ok?: boolean; status?: number; contentRange?: string } = {},
|
|
15
|
-
):
|
|
16
|
+
): FetchMock {
|
|
16
17
|
const { ok = true, status = ok ? 200 : 400, contentRange } = opts
|
|
17
|
-
return
|
|
18
|
-
ok,
|
|
19
|
-
status,
|
|
20
|
-
json: vi.fn().mockResolvedValue(body),
|
|
21
|
-
text: vi.fn().mockResolvedValue(JSON.stringify(body)),
|
|
22
|
-
headers: {
|
|
23
|
-
get: (key: string) => (key === "content-range" ? (contentRange ?? null) : null),
|
|
24
|
-
},
|
|
25
|
-
})
|
|
18
|
+
return fetchReturning(body, status, contentRange === undefined ? {} : { "Content-Range": contentRange })
|
|
26
19
|
}
|
|
27
20
|
|
|
28
|
-
function captureUrl(): { url: () => string; fetch:
|
|
21
|
+
function captureUrl(): { url: () => string; fetch: FetchMock } {
|
|
29
22
|
const fetch = mockFetch([])
|
|
30
23
|
vi.stubGlobal("fetch", fetch)
|
|
31
24
|
return {
|
|
32
25
|
fetch,
|
|
33
|
-
url: () => (fetch.
|
|
26
|
+
url: () => fetchCall(fetch).url,
|
|
34
27
|
}
|
|
35
28
|
}
|
|
36
29
|
|
|
@@ -126,6 +119,17 @@ describe("QueryBuilder: URL construction", () => {
|
|
|
126
119
|
expect(url()).toContain("nullsfirst")
|
|
127
120
|
})
|
|
128
121
|
|
|
122
|
+
// PostgREST reads only the first `order` parameter, so a second one sent separately was dropped
|
|
123
|
+
// without an error and the rows came back ordered by the first column alone.
|
|
124
|
+
it(".order() twice sends one comma-separated order parameter", async () => {
|
|
125
|
+
const { url } = captureUrl()
|
|
126
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS)
|
|
127
|
+
.order("created_at", { ascending: false })
|
|
128
|
+
.order("id", { ascending: false })
|
|
129
|
+
const params = new URL(url()).searchParams
|
|
130
|
+
expect(params.getAll("order")).toEqual(["created_at.desc.nullslast,id.desc.nullslast"])
|
|
131
|
+
})
|
|
132
|
+
|
|
129
133
|
it(".limit() sets limit param", async () => {
|
|
130
134
|
const { url } = captureUrl()
|
|
131
135
|
await new QueryBuilder<Post>(BASE, PATH, HEADERS).limit(20)
|
|
@@ -136,8 +140,7 @@ describe("QueryBuilder: URL construction", () => {
|
|
|
136
140
|
const fetch = mockFetch([])
|
|
137
141
|
vi.stubGlobal("fetch", fetch)
|
|
138
142
|
await new QueryBuilder<Post>(BASE, PATH, HEADERS).range(10, 19)
|
|
139
|
-
|
|
140
|
-
expect((opts.headers as Record<string, string>)["Range"]).toBe("10-19")
|
|
143
|
+
expect(header(fetchCall(fetch).init, "Range")).toBe("10-19")
|
|
141
144
|
})
|
|
142
145
|
|
|
143
146
|
it("multiple chained filters all appear in URL", async () => {
|
|
@@ -166,8 +169,7 @@ describe("QueryBuilder: URL construction", () => {
|
|
|
166
169
|
await new QueryBuilder<Post>(BASE, PATH, HEADERS, "*", defaultQueryCache, undefined, {
|
|
167
170
|
count: "exact",
|
|
168
171
|
})
|
|
169
|
-
|
|
170
|
-
expect((opts.headers as Record<string, string>)["Prefer"]).toBe("count=exact")
|
|
172
|
+
expect(header(fetchCall(fetch).init, "Prefer")).toBe("count=exact")
|
|
171
173
|
})
|
|
172
174
|
|
|
173
175
|
it("select with head issues HEAD request and returns count only", async () => {
|
|
@@ -182,8 +184,7 @@ describe("QueryBuilder: URL construction", () => {
|
|
|
182
184
|
undefined,
|
|
183
185
|
{ count: "exact", head: true },
|
|
184
186
|
)
|
|
185
|
-
|
|
186
|
-
expect(opts.method).toBe("HEAD")
|
|
187
|
+
expect(fetchCall(fetch).init.method).toBe("HEAD")
|
|
187
188
|
expect(data).toBeNull()
|
|
188
189
|
expect(error).toBeNull()
|
|
189
190
|
expect(count).toBe(42)
|
|
@@ -231,8 +232,7 @@ describe("QueryBuilder.single()", () => {
|
|
|
231
232
|
const fetch = mockFetch({ id: "1", title: "Hello", status: "published" })
|
|
232
233
|
vi.stubGlobal("fetch", fetch)
|
|
233
234
|
await new QueryBuilder<Post>(BASE, PATH, HEADERS).single()
|
|
234
|
-
|
|
235
|
-
expect((opts.headers as Record<string, string>)["Accept"]).toContain("pgrst.object+json")
|
|
235
|
+
expect(header(fetchCall(fetch).init, "Accept")).toContain("pgrst.object+json")
|
|
236
236
|
})
|
|
237
237
|
|
|
238
238
|
it("returns single row", async () => {
|
|
@@ -271,9 +271,9 @@ describe("MutationBuilder: insert", () => {
|
|
|
271
271
|
const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" })
|
|
272
272
|
expect(error).toBeNull()
|
|
273
273
|
expect(data?.[0]?.id).toBe("1")
|
|
274
|
-
const
|
|
275
|
-
expect(
|
|
276
|
-
expect(
|
|
274
|
+
const { init } = fetchCall(fetch)
|
|
275
|
+
expect(init.method).toBe("POST")
|
|
276
|
+
expect(init.body).toContain("New")
|
|
277
277
|
})
|
|
278
278
|
|
|
279
279
|
it("returns error on non-ok", async () => {
|
|
@@ -291,8 +291,8 @@ describe("MutationBuilder: update / delete", () => {
|
|
|
291
291
|
const fetch = mockFetch([{ id: "1", title: "Updated", status: "published" }])
|
|
292
292
|
vi.stubGlobal("fetch", fetch)
|
|
293
293
|
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "PATCH", { title: "Updated" }).eq("id", "1")
|
|
294
|
-
const
|
|
295
|
-
expect(
|
|
294
|
+
const { url, init } = fetchCall(fetch)
|
|
295
|
+
expect(init.method).toBe("PATCH")
|
|
296
296
|
expect(url).toContain("id=eq.1")
|
|
297
297
|
})
|
|
298
298
|
|
|
@@ -300,8 +300,8 @@ describe("MutationBuilder: update / delete", () => {
|
|
|
300
300
|
const fetch = mockFetch(null, { status: 204 })
|
|
301
301
|
vi.stubGlobal("fetch", fetch)
|
|
302
302
|
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
|
|
303
|
-
const
|
|
304
|
-
expect(
|
|
303
|
+
const { url, init } = fetchCall(fetch)
|
|
304
|
+
expect(init.method).toBe("DELETE")
|
|
305
305
|
expect(url).toContain("id=eq.1")
|
|
306
306
|
})
|
|
307
307
|
|
|
@@ -316,8 +316,7 @@ describe("MutationBuilder: update / delete", () => {
|
|
|
316
316
|
const fetch = mockFetch([{ id: "1", title: "A", status: "draft" }])
|
|
317
317
|
vi.stubGlobal("fetch", fetch)
|
|
318
318
|
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { id: "1", title: "A", status: "draft" }, { upsert: true })
|
|
319
|
-
|
|
320
|
-
expect((opts.headers as Record<string, string>)["Prefer"]).toContain("merge-duplicates")
|
|
319
|
+
expect(header(fetchCall(fetch).init, "Prefer")).toContain("merge-duplicates")
|
|
321
320
|
})
|
|
322
321
|
|
|
323
322
|
it("update().eq().select().maybeSingle() returns first row", async () => {
|
|
@@ -335,7 +334,6 @@ describe("MutationBuilder: update / delete", () => {
|
|
|
335
334
|
.maybeSingle()
|
|
336
335
|
expect(error).toBeNull()
|
|
337
336
|
expect(data).toEqual({ id: "1", title: "Updated", status: "published" })
|
|
338
|
-
|
|
339
|
-
expect(url).toContain("select=*")
|
|
337
|
+
expect(fetchCall(fetch).url).toContain("select=*")
|
|
340
338
|
})
|
|
341
339
|
})
|
|
@@ -11,14 +11,8 @@ import { RateLimitError } from "../src/errors.js"
|
|
|
11
11
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
12
12
|
|
|
13
13
|
function mockResponse(status: number, body: unknown = {}, headers?: Record<string, string>): Response {
|
|
14
|
-
const
|
|
15
|
-
return {
|
|
16
|
-
ok: status >= 200 && status < 300,
|
|
17
|
-
status,
|
|
18
|
-
json: vi.fn().mockResolvedValue(body),
|
|
19
|
-
headers: headersObj,
|
|
20
|
-
statusText: status === 429 ? "Too Many Requests" : "OK",
|
|
21
|
-
} as unknown as Response
|
|
14
|
+
const statusText = status === 429 ? "Too Many Requests" : "OK"
|
|
15
|
+
return new Response(JSON.stringify(body), { status, statusText, headers: { "Content-Type": "application/json", ...headers } })
|
|
22
16
|
}
|
|
23
17
|
|
|
24
18
|
// ─── Tests ───────────────────────────────────────────────────────────────────
|
|
@@ -126,9 +120,7 @@ describe("Task 91: SDK rate limit integration", () => {
|
|
|
126
120
|
expect.fail("Should have thrown RateLimitError")
|
|
127
121
|
} catch (err) {
|
|
128
122
|
expect(err).toBeInstanceOf(RateLimitError)
|
|
129
|
-
expect(
|
|
130
|
-
expect((err as RateLimitError).statusCode).toBe(429)
|
|
131
|
-
expect((err as RateLimitError).code).toBe("RATE_LIMITED")
|
|
123
|
+
expect(err).toMatchObject({ retryAfterSeconds: 2, statusCode: 429, code: "RATE_LIMITED" })
|
|
132
124
|
}
|
|
133
125
|
vi.useFakeTimers()
|
|
134
126
|
})
|
|
@@ -179,7 +171,7 @@ describe("Task 91: SDK rate limit integration", () => {
|
|
|
179
171
|
|
|
180
172
|
const res = await promise
|
|
181
173
|
expect(res.ok).toBe(true)
|
|
182
|
-
const data = await res.json()
|
|
174
|
+
const data: unknown = await res.json()
|
|
183
175
|
expect(data).toEqual(expectedData)
|
|
184
176
|
})
|
|
185
177
|
})
|
|
@@ -22,17 +22,15 @@ import {
|
|
|
22
22
|
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
|
|
23
23
|
|
|
24
24
|
let instances: MockWebSocketInstance[]
|
|
25
|
-
let originalWebSocket: typeof WebSocket
|
|
26
25
|
|
|
27
26
|
beforeEach(() => {
|
|
28
27
|
const mock = createMockWebSocketClass()
|
|
29
28
|
instances = mock.instances
|
|
30
|
-
|
|
31
|
-
globalThis.WebSocket = mock.MockWebSocket
|
|
29
|
+
vi.stubGlobal("WebSocket", mock.MockWebSocket)
|
|
32
30
|
})
|
|
33
31
|
|
|
34
32
|
afterEach(() => {
|
|
35
|
-
|
|
33
|
+
vi.unstubAllGlobals()
|
|
36
34
|
vi.restoreAllMocks()
|
|
37
35
|
})
|
|
38
36
|
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Presence counted from joins and leaves stays true across a socket swap.
|
|
3
|
+
*
|
|
4
|
+
* The server tells a channel's newcomer who is already there as joins, and it does so on every
|
|
5
|
+
* join, including the one each channel makes again on the socket that signing in opens. Leaves
|
|
6
|
+
* for the old socket's members never arrive (that socket is gone), so a page counting joins minus
|
|
7
|
+
* leaves read every member twice after signing in. The client now leaves, for its listeners,
|
|
8
|
+
* everyone it had been told about when the socket that told it goes away.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, it, expect, beforeEach, afterEach } from "vitest"
|
|
12
|
+
import type { PresenceEntry } from "../src/realtime.js"
|
|
13
|
+
import { simulateServerMessage } from "./helpers/mock-websocket.js"
|
|
14
|
+
import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
|
|
15
|
+
|
|
16
|
+
const CHANNEL = "lobby:lobby"
|
|
17
|
+
|
|
18
|
+
let harness: SocketSwapHarness
|
|
19
|
+
let here: number
|
|
20
|
+
let leaves: PresenceEntry[]
|
|
21
|
+
|
|
22
|
+
function newest(): SocketSwapHarness["sockets"][number] {
|
|
23
|
+
const socket = harness.sockets[harness.sockets.length - 1]
|
|
24
|
+
if (socket === undefined) throw new Error("no socket has been opened")
|
|
25
|
+
return socket
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function serverSays(joins: PresenceEntry[], left: PresenceEntry[] = []): void {
|
|
29
|
+
simulateServerMessage(newest(), { type: "presence", channel: CHANNEL, joins, leaves: left })
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
beforeEach(async () => {
|
|
33
|
+
harness = createSocketSwapHarness()
|
|
34
|
+
here = 0
|
|
35
|
+
leaves = []
|
|
36
|
+
const channel = harness.realtime.channel(CHANNEL)
|
|
37
|
+
channel.onPresence((event) => {
|
|
38
|
+
here += event.joins.length - event.leaves.length
|
|
39
|
+
leaves.push(...event.leaves)
|
|
40
|
+
})
|
|
41
|
+
channel.subscribe()
|
|
42
|
+
await harness.settle()
|
|
43
|
+
harness.ackJoins()
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
afterEach(() => harness.restore())
|
|
47
|
+
|
|
48
|
+
describe("presence across the socket swap on sign-in", () => {
|
|
49
|
+
it("counts each member once after the new socket's join sends the state again", async () => {
|
|
50
|
+
serverSays([{ user_id: "first" }, { user_id: "second" }])
|
|
51
|
+
expect(here).toBe(2)
|
|
52
|
+
|
|
53
|
+
await harness.signIn()
|
|
54
|
+
harness.ackJoins()
|
|
55
|
+
serverSays([{ user_id: "first" }, { user_id: "second" }])
|
|
56
|
+
|
|
57
|
+
expect(here).toBe(2)
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it("leaves everyone it had been told about when the socket goes away", async () => {
|
|
61
|
+
serverSays([{ user_id: "first" }, { user_id: "second" }])
|
|
62
|
+
serverSays([], [{ user_id: "first" }])
|
|
63
|
+
|
|
64
|
+
await harness.signIn()
|
|
65
|
+
|
|
66
|
+
expect(here).toBe(0)
|
|
67
|
+
expect(leaves).toEqual([{ user_id: "first" }, { user_id: "second" }])
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
it("tells a channel nobody joined nothing when the socket goes away", () => {
|
|
71
|
+
harness.realtime.disconnect()
|
|
72
|
+
|
|
73
|
+
expect(leaves).toEqual([])
|
|
74
|
+
})
|
|
75
|
+
})
|
|
@@ -16,6 +16,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
|
16
16
|
import { RealtimeClient } from "../src/realtime.js"
|
|
17
17
|
import {
|
|
18
18
|
createMockWebSocketClass,
|
|
19
|
+
subscribedChannels,
|
|
19
20
|
tokenOf,
|
|
20
21
|
type MockWebSocketInstance,
|
|
21
22
|
} from "./helpers/mock-websocket.js"
|
|
@@ -128,10 +129,7 @@ describe("realtime authenticates as the session, not as anon", () => {
|
|
|
128
129
|
await settle()
|
|
129
130
|
|
|
130
131
|
const replacement = MockWS.instances[1]!
|
|
131
|
-
|
|
132
|
-
.map(([raw]) => JSON.parse(String(raw)) as { type: string; channel: string })
|
|
133
|
-
.filter((m) => m.type === "subscribe")
|
|
134
|
-
expect(subscribes.map((m) => m.channel)).toContain("public:task")
|
|
132
|
+
expect(subscribedChannels(replacement)).toContain("public:task")
|
|
135
133
|
})
|
|
136
134
|
|
|
137
135
|
it("reconnects when the identity changes while the first connect is still resolving its token", async () => {
|