@supatype/client 0.9.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +76 -68
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +82 -0
- package/dist/auth.d.ts +50 -6
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +117 -32
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +3 -0
- package/dist/bindings.d.ts.map +1 -1
- package/dist/bindings.js +2 -0
- package/dist/bindings.js.map +1 -1
- 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 +7 -0
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +81 -21
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +133 -46
- package/dist/errors.js.map +1 -1
- package/dist/graphql-transport.d.ts +8 -1
- package/dist/graphql-transport.d.ts.map +1 -1
- package/dist/graphql-transport.js +5 -5
- package/dist/graphql-transport.js.map +1 -1
- package/dist/index.d.ts +10 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +52 -37
- package/dist/index.js.map +1 -1
- package/dist/latest-rows.d.ts +44 -0
- package/dist/latest-rows.d.ts.map +1 -0
- package/dist/latest-rows.js +58 -0
- package/dist/latest-rows.js.map +1 -0
- package/dist/mutation-request.d.ts +2 -1
- package/dist/mutation-request.d.ts.map +1 -1
- package/dist/mutation-request.js +2 -1
- package/dist/mutation-request.js.map +1 -1
- package/dist/page-env-script.d.ts +12 -0
- package/dist/page-env-script.d.ts.map +1 -0
- package/dist/page-env-script.js +30 -0
- package/dist/page-env-script.js.map +1 -0
- package/dist/preview.d.ts +2 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +7 -3
- package/dist/preview.js.map +1 -1
- package/dist/query.d.ts +18 -5
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +33 -16
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +22 -8
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +121 -41
- package/dist/realtime.js.map +1 -1
- package/dist/runtime-env.d.ts +59 -0
- package/dist/runtime-env.d.ts.map +1 -0
- package/dist/runtime-env.js +202 -0
- package/dist/runtime-env.js.map +1 -0
- package/dist/setup-fault.d.ts +13 -0
- package/dist/setup-fault.d.ts.map +1 -0
- package/dist/setup-fault.js +17 -0
- package/dist/setup-fault.js.map +1 -0
- package/dist/storage.d.ts +10 -5
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +22 -13
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +5 -3
- package/dist/table-subscription.d.ts.map +1 -1
- package/dist/table-subscription.js +8 -5
- package/dist/table-subscription.js.map +1 -1
- package/dist/thrown-error.d.ts +16 -0
- package/dist/thrown-error.d.ts.map +1 -0
- package/dist/thrown-error.js +31 -0
- package/dist/thrown-error.js.map +1 -0
- package/dist/types.d.ts +64 -15
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -1
- package/src/auth.ts +121 -36
- package/src/bindings.ts +3 -0
- package/src/error-codes-doc.ts +9 -1
- package/src/errors.ts +155 -57
- package/src/graphql-transport.ts +5 -6
- package/src/index.ts +63 -45
- package/src/latest-rows.ts +95 -0
- package/src/mutation-request.ts +3 -2
- package/src/page-env-script.ts +27 -0
- package/src/preview.ts +8 -4
- package/src/query.ts +38 -19
- package/src/realtime.ts +146 -44
- package/src/runtime-env.ts +262 -0
- package/src/setup-fault.ts +18 -0
- package/src/storage.ts +26 -16
- package/src/table-subscription.ts +8 -6
- package/src/thrown-error.ts +31 -0
- package/src/types.ts +70 -14
- package/tests/auth-errors.test.ts +3 -3
- package/tests/auth-events.test.ts +3 -7
- package/tests/auth-sso.test.ts +291 -0
- package/tests/auth-url-session.test.ts +6 -25
- package/tests/entry-points.test.ts +9 -0
- package/tests/error-family.test.ts +79 -0
- package/tests/examples-runtime-env.test.ts +135 -0
- package/tests/helpers/auth-unmount-binding.ts +63 -0
- package/tests/helpers/mock-websocket.ts +22 -0
- package/tests/helpers/oauth-binding.ts +4 -3
- package/tests/helpers/reactive-options-binding.ts +99 -0
- package/tests/helpers/stale-read-binding.ts +113 -0
- package/tests/helpers/thrown-error-binding.ts +127 -0
- package/tests/postgrest-error-codes.test.ts +4 -4
- package/tests/query.test.ts +39 -2
- package/tests/rate-limit-integration.test.ts +1 -1
- package/tests/realtime-multi-tenant-integration.test.ts +0 -1
- package/tests/realtime-refusal-error.test.ts +79 -0
- package/tests/realtime-rows-after-broadcast.test.ts +205 -0
- package/tests/realtime-session-auth.test.ts +0 -1
- package/tests/realtime-shared-channel.test.ts +9 -27
- package/tests/result-error-class.test.ts +107 -0
- package/tests/retry-policy.test.ts +1 -1
- package/tests/runtime-env-bundle.test.ts +121 -0
- package/tests/runtime-env-expo.test.ts +58 -0
- package/tests/runtime-env-page-script.test.ts +174 -0
- package/tests/runtime-env.test.ts +259 -0
- package/tests/server-bodies.test.ts +3 -3
- package/tests/subscribe-frame.test.ts +48 -0
- package/tests/support/browser.ts +28 -0
- package/tests/support/jwt.ts +5 -0
- package/tests/thrown-error.test.ts +59 -0
- package/tsconfig.json +2 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { AnyClient } from "./index.js"
|
|
2
|
+
import type { SupatypeError } from "./types.js"
|
|
3
|
+
import { isRowsOf } from "./caller-types.js"
|
|
4
|
+
import { reportThrown } from "./thrown-error.js"
|
|
5
|
+
|
|
6
|
+
/** The read the Vue, Svelte and Solid queries make: columns, equality filters, order and a page. */
|
|
7
|
+
export interface RowsReadOptions {
|
|
8
|
+
columns?: string | undefined
|
|
9
|
+
filter?: Record<string, unknown> | undefined
|
|
10
|
+
order?: { column: string; ascending?: boolean | undefined } | undefined
|
|
11
|
+
limit?: number | undefined
|
|
12
|
+
offset?: number | undefined
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Where a binding shows its reads: one started, and the newest one's answer. */
|
|
16
|
+
export interface RowsView<TRow> {
|
|
17
|
+
started(): void
|
|
18
|
+
settled(data: TRow[] | null, error: SupatypeError | null): void
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A binding's reads of one table, where only the newest may change what it shows.
|
|
23
|
+
*
|
|
24
|
+
* A refetch while a read is in flight puts two reads on the wire, and the older can land last;
|
|
25
|
+
* its answer, a returned error or a throw, is dropped rather than replacing the newer one's. A
|
|
26
|
+
* read that throws (a client with no API address, say) ends like one that was refused, and is
|
|
27
|
+
* reported once with `console.error` even when a newer read has replaced it. `where` names the
|
|
28
|
+
* binding in that report.
|
|
29
|
+
*/
|
|
30
|
+
export function latestRowsReader<TRow>(
|
|
31
|
+
client: AnyClient,
|
|
32
|
+
table: string,
|
|
33
|
+
where: string,
|
|
34
|
+
view: RowsView<TRow>,
|
|
35
|
+
): (options: RowsReadOptions | undefined) => Promise<void> {
|
|
36
|
+
let latest = 0
|
|
37
|
+
return async (options) => {
|
|
38
|
+
const request = ++latest
|
|
39
|
+
view.started()
|
|
40
|
+
const answer = await answerOf<TRow>(client, table, where, options)
|
|
41
|
+
if (request === latest) view.settled(answer.data, answer.error)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function answerOf<TRow>(
|
|
46
|
+
client: AnyClient,
|
|
47
|
+
table: string,
|
|
48
|
+
where: string,
|
|
49
|
+
options: RowsReadOptions | undefined,
|
|
50
|
+
): Promise<{ data: TRow[] | null; error: SupatypeError | null }> {
|
|
51
|
+
try {
|
|
52
|
+
const result = await readRows(client, table, options)
|
|
53
|
+
return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error }
|
|
54
|
+
} catch (e) {
|
|
55
|
+
return { data: null, error: reportThrown(where, e) }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The read `options` describe. Through the untyped client: the generated row types do not survive
|
|
61
|
+
* a table name known only at run time, so the binding types the rows as `TRow` once they arrive.
|
|
62
|
+
*/
|
|
63
|
+
function readRows(client: AnyClient, table: string, options: RowsReadOptions | undefined) {
|
|
64
|
+
let query = client.from(table).select(options?.columns)
|
|
65
|
+
for (const [col, val] of Object.entries(options?.filter ?? {})) {
|
|
66
|
+
query = query.eq(col, val)
|
|
67
|
+
}
|
|
68
|
+
if (options?.order !== undefined) {
|
|
69
|
+
query = query.order(options.order.column, { ascending: options.order.ascending ?? true })
|
|
70
|
+
}
|
|
71
|
+
return withPage(query, options)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** How many rows a binding's query reads from an `offset` given with no `limit`. */
|
|
75
|
+
const DEFAULT_PAGE_SIZE = 100
|
|
76
|
+
|
|
77
|
+
/** A query a page can be applied to: the client's `QueryBuilder`, whatever its row type. */
|
|
78
|
+
interface Pageable<Q> {
|
|
79
|
+
limit(count: number): Q
|
|
80
|
+
range(from: number, to: number): Q
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* `query` limited to the page `limit` and `offset` describe, for every binding's query. An offset
|
|
85
|
+
* with no limit reads `DEFAULT_PAGE_SIZE` rows: React's `useQuery` used to drop the offset there
|
|
86
|
+
* while the Vue, Svelte and Solid queries read 100, so the same options read different rows.
|
|
87
|
+
*/
|
|
88
|
+
export function withPage<Q extends Pageable<Q>>(
|
|
89
|
+
query: Q,
|
|
90
|
+
page: { limit?: number | undefined; offset?: number | undefined } | undefined,
|
|
91
|
+
): Q {
|
|
92
|
+
const limited = page?.limit !== undefined ? query.limit(page.limit) : query
|
|
93
|
+
if (page?.offset === undefined) return limited
|
|
94
|
+
return limited.range(page.offset, page.offset + (page.limit ?? DEFAULT_PAGE_SIZE) - 1)
|
|
95
|
+
}
|
package/src/mutation-request.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AnyClient } from "./index.js"
|
|
2
|
-
import type { DraftUpdateOptions, QueryResult
|
|
2
|
+
import type { DraftUpdateOptions, QueryResult } from "./types.js"
|
|
3
|
+
import { SupatypeError } from "./errors.js"
|
|
3
4
|
import { isRowsOf } from "./caller-types.js"
|
|
4
5
|
|
|
5
6
|
export type MutationOperation = "insert" | "update" | "delete" | "upsert"
|
|
@@ -74,7 +75,7 @@ export async function runMutation<TRow>(
|
|
|
74
75
|
request: MutationRequest = {},
|
|
75
76
|
): Promise<MutationOutcome<TRow>> {
|
|
76
77
|
const pending = mutationRequest(client.from(table), operation, data, request)
|
|
77
|
-
if (typeof pending === "string") return { data: null, error: { message: pending }, count: null }
|
|
78
|
+
if (typeof pending === "string") return { data: null, error: new SupatypeError({ message: pending }), count: null }
|
|
78
79
|
const result = await pending
|
|
79
80
|
return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error, count: result.count }
|
|
80
81
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page's `<script src=".../supatype-env.js">` element, when it has one.
|
|
3
|
+
*
|
|
4
|
+
* A page that has the element and still no `window.__SUPATYPE_ENV__` did not run the script: it was
|
|
5
|
+
* blocked, failed to load, ran after the app's own script, or came from a server too old to serve
|
|
6
|
+
* it. A misconfigured server still answers 200 with a script setting `error`, so a missing global
|
|
7
|
+
* never means the server refused. The error a request throws then says the script is there and to
|
|
8
|
+
* open it, not to add it.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** The absolute address of the page's `/supatype-env.js` script, or undefined when it has none. */
|
|
12
|
+
export function pageEnvScript(): string | undefined {
|
|
13
|
+
if (typeof document === "undefined") return undefined
|
|
14
|
+
for (const script of Array.from(document.scripts)) {
|
|
15
|
+
if (isEnvScript(script.src)) return script.src
|
|
16
|
+
}
|
|
17
|
+
return undefined
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function isEnvScript(src: string): boolean {
|
|
21
|
+
if (src === "") return false
|
|
22
|
+
try {
|
|
23
|
+
return new URL(src).pathname.endsWith("/supatype-env.js")
|
|
24
|
+
} catch {
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
}
|
package/src/preview.ts
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
23
|
import { readJsonObject } from "./json.js"
|
|
24
|
+
import { settle, type Deferred } from "./runtime-env.js"
|
|
24
25
|
|
|
25
26
|
/** Milliseconds of slack before expiry at which the token is treated as spent. */
|
|
26
27
|
const REFRESH_SKEW_MS = 5_000
|
|
@@ -47,14 +48,14 @@ export class PreviewLinkError extends Error {
|
|
|
47
48
|
* for as long as any request is outstanding, and this needs two strings.
|
|
48
49
|
*/
|
|
49
50
|
export class PreviewCredential {
|
|
50
|
-
readonly #
|
|
51
|
+
readonly #baseUrl: Deferred<string>
|
|
51
52
|
readonly #code: string
|
|
52
53
|
#token: string | null = null
|
|
53
54
|
#expiresAtMs = 0
|
|
54
55
|
#inFlight: Promise<string> | null = null
|
|
55
56
|
|
|
56
|
-
constructor(baseUrl: string
|
|
57
|
-
this.#
|
|
57
|
+
constructor(baseUrl: Deferred<string>, code: string) {
|
|
58
|
+
this.#baseUrl = baseUrl
|
|
58
59
|
this.#code = code
|
|
59
60
|
}
|
|
60
61
|
|
|
@@ -71,9 +72,12 @@ export class PreviewCredential {
|
|
|
71
72
|
}
|
|
72
73
|
|
|
73
74
|
async #exchange(): Promise<string> {
|
|
75
|
+
// Read before the request rather than inside it: a client with no address throws the error that
|
|
76
|
+
// says so, not one calling the link invalid.
|
|
77
|
+
const endpoint = `${settle(this.#baseUrl).replace(/\/$/, "")}/preview-links/resolve`
|
|
74
78
|
let response: Response
|
|
75
79
|
try {
|
|
76
|
-
response = await fetch(
|
|
80
|
+
response = await fetch(endpoint, {
|
|
77
81
|
method: "POST",
|
|
78
82
|
headers: { "Content-Type": "application/json" },
|
|
79
83
|
body: JSON.stringify({ code: this.#code }),
|
package/src/query.ts
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import type { QueryCache, QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
2
2
|
import { buildCacheKey, defaultQueryCache } from "./query-cache.js"
|
|
3
|
-
import type { MaskedField, QueryResult, SelectQueryOptions,
|
|
3
|
+
import type { MaskedField, QueryResult, SelectQueryOptions, TableDef } from "./types.js"
|
|
4
4
|
import { DRAFT_SCHEMA, PUBLISHING_SCHEMA } from "./types.js"
|
|
5
5
|
import { createCall, createdKeys, inCreatedOrder, readBackColumns } from "./draft-create.js"
|
|
6
6
|
import type { SelectRow } from "./select-types.js"
|
|
7
7
|
import { parseRowsExactly, tableFromPath } from "./exact-response.js"
|
|
8
8
|
import { stringifyWithBigInts } from "./exact-values.js"
|
|
9
9
|
import { FilterBuilder } from "./filters.js"
|
|
10
|
-
import { PostgrestErrorCodes, transportFailure } from "./errors.js"
|
|
10
|
+
import { PostgrestErrorCodes, SupatypeError, transportFailure } from "./errors.js"
|
|
11
11
|
import { plainFetch, type FetchOptions, type RequestTransport } from "./fetch-with-retry.js"
|
|
12
12
|
import { isJsonObject, isOneOf, readJsonObject, refusalText } from "./json.js"
|
|
13
13
|
import { bearerRole } from "./jwt.js"
|
|
14
|
+
import { settle, type Deferred } from "./runtime-env.js"
|
|
14
15
|
|
|
15
16
|
const DEBUG_AUTH =
|
|
16
17
|
(typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1") ||
|
|
@@ -35,7 +36,7 @@ function callerRows<TRow>(value: unknown): TRow[] | null {
|
|
|
35
36
|
|
|
36
37
|
/** The body was JSON but not rows: PostgREST does not answer a table request that way. */
|
|
37
38
|
function notRows(status: number): SupatypeError {
|
|
38
|
-
return { message: `Unexpected response body: expected rows (HTTP ${status})`, status }
|
|
39
|
+
return new SupatypeError({ message: `Unexpected response body: expected rows (HTTP ${status})`, status })
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
/**
|
|
@@ -64,7 +65,7 @@ export function parseMaskedFields(header: string | null): MaskedField[] | undefi
|
|
|
64
65
|
* the same error whether PostgREST refused the request or the client found the rows wrong.
|
|
65
66
|
*/
|
|
66
67
|
function notOneRow(): SupatypeError {
|
|
67
|
-
return { message: "Cannot coerce the result to a single JSON object", code: PostgrestErrorCodes.NOT_FOUND }
|
|
68
|
+
return new SupatypeError({ message: "Cannot coerce the result to a single JSON object", code: PostgrestErrorCodes.NOT_FOUND })
|
|
68
69
|
}
|
|
69
70
|
|
|
70
71
|
/**
|
|
@@ -74,7 +75,7 @@ function notOneRow(): SupatypeError {
|
|
|
74
75
|
* validator only ever runs on a write, so the column it named never reached the caller.
|
|
75
76
|
*/
|
|
76
77
|
function refusal(err: Record<string, unknown>, status: number): SupatypeError {
|
|
77
|
-
return {
|
|
78
|
+
return new SupatypeError({
|
|
78
79
|
message: refusalText(err) ?? String(err["hint"] ?? "Request failed"),
|
|
79
80
|
status,
|
|
80
81
|
...(err["code"] !== undefined && { code: String(err["code"]) }),
|
|
@@ -83,7 +84,7 @@ function refusal(err: Record<string, unknown>, status: number): SupatypeError {
|
|
|
83
84
|
...(typeof err["field"] === "string" && { field: err["field"] }),
|
|
84
85
|
...(typeof err["hint"] === "string" && err["hint"] !== "" && { hint: err["hint"] }),
|
|
85
86
|
...(typeof err["details"] === "string" && err["details"] !== "" && { details: err["details"] }),
|
|
86
|
-
}
|
|
87
|
+
})
|
|
87
88
|
}
|
|
88
89
|
|
|
89
90
|
/** The refusal a failed request answered with, logged with `context` when auth debugging is on. */
|
|
@@ -112,7 +113,7 @@ async function readRefusal(
|
|
|
112
113
|
*/
|
|
113
114
|
function readRows<TRow>(body: string, path: string, status: number, count: number | null): QueryResult<TRow[]> {
|
|
114
115
|
const parsed = parseRowsExactly(body, tableFromPath(path))
|
|
115
|
-
if (!parsed.ok) return { data: null, error: { message: parsed.message, status }, count: null }
|
|
116
|
+
if (!parsed.ok) return { data: null, error: new SupatypeError({ message: parsed.message, status }), count: null }
|
|
116
117
|
const rows = callerRows<TRow>(parsed.value)
|
|
117
118
|
if (rows === null) return { data: null, error: notRows(status), count: null }
|
|
118
119
|
return { data: rows, error: null, count }
|
|
@@ -232,7 +233,7 @@ export function parseContentRangeTotal(header: string | null): number | null {
|
|
|
232
233
|
// ─── QueryBuilder ─────────────────────────────────────────────────────────────
|
|
233
234
|
|
|
234
235
|
export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<QueryResult<TRow[]>> {
|
|
235
|
-
private readonly
|
|
236
|
+
private readonly base: Deferred<string>
|
|
236
237
|
private readonly path: string
|
|
237
238
|
private readonly getHeaders: HeadersProvider
|
|
238
239
|
private readonly onUnauthorized: UnauthorizedHandler | undefined
|
|
@@ -244,7 +245,7 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
|
|
|
244
245
|
private readonly head: boolean
|
|
245
246
|
|
|
246
247
|
constructor(
|
|
247
|
-
baseUrl: string
|
|
248
|
+
baseUrl: Deferred<string>,
|
|
248
249
|
path: string,
|
|
249
250
|
headers: Record<string, string> | HeadersProvider,
|
|
250
251
|
columns?: string | undefined,
|
|
@@ -254,7 +255,7 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
|
|
|
254
255
|
transport: RequestTransport = plainFetch,
|
|
255
256
|
) {
|
|
256
257
|
super()
|
|
257
|
-
this.
|
|
258
|
+
this.base = baseUrl
|
|
258
259
|
this.path = path
|
|
259
260
|
this.getHeaders = asHeadersProvider(headers)
|
|
260
261
|
this.onUnauthorized = onUnauthorized
|
|
@@ -313,9 +314,16 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
|
|
|
313
314
|
return this
|
|
314
315
|
}
|
|
315
316
|
|
|
317
|
+
/**
|
|
318
|
+
* Rows `from` to `to`, both inclusive and counted from 0. Sent as `offset` and `limit`, the
|
|
319
|
+
* same parameters `limit()` writes, so whichever of the two is called last sets the page size,
|
|
320
|
+
* as in supabase-js. 0.9.1 release test (FF15): it was a `Range` header, which PostgREST
|
|
321
|
+
* refuses with 416 PGRST103 beside a `limit` parameter, and which the read cache's key (the
|
|
322
|
+
* URL) did not include, so a cached second page answered with the first.
|
|
323
|
+
*/
|
|
316
324
|
range(from: number, to: number): this {
|
|
317
|
-
this.
|
|
318
|
-
this.
|
|
325
|
+
this.params.set("offset", String(from))
|
|
326
|
+
this.params.set("limit", String(to - from + 1))
|
|
319
327
|
return this
|
|
320
328
|
}
|
|
321
329
|
|
|
@@ -354,6 +362,11 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
|
|
|
354
362
|
return this._fetch({}).then(onfulfilled, onrejected)
|
|
355
363
|
}
|
|
356
364
|
|
|
365
|
+
/** The address, read now: a deferred one is only known when the request is sent. */
|
|
366
|
+
private get baseUrl(): string {
|
|
367
|
+
return settle(this.base)
|
|
368
|
+
}
|
|
369
|
+
|
|
357
370
|
private buildRequestUrl(): string {
|
|
358
371
|
const qs = this.params.toString()
|
|
359
372
|
return `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
|
|
@@ -524,7 +537,7 @@ function isWriteResult<TResult>(value: unknown): value is TResult {
|
|
|
524
537
|
/** `single()` or `maybeSingle()` on a write that asked for no rows, refused before anything is sent. */
|
|
525
538
|
function rowNotSelected(): { data: null; error: SupatypeError; count: null } {
|
|
526
539
|
const message = "A write returns no rows until select() asks for them: call select() before single() or maybeSingle()"
|
|
527
|
-
return { data: null, error: { message }, count: null }
|
|
540
|
+
return { data: null, error: new SupatypeError({ message }), count: null }
|
|
528
541
|
}
|
|
529
542
|
|
|
530
543
|
/**
|
|
@@ -538,7 +551,7 @@ function rowNotSelected(): { data: null; error: SupatypeError; count: null } {
|
|
|
538
551
|
export class MutationBuilder<TRow, TTables = unknown, TName extends string = string, TResult = null>
|
|
539
552
|
extends FilterBuilder
|
|
540
553
|
implements PromiseLike<QueryResult<TResult>> {
|
|
541
|
-
private readonly
|
|
554
|
+
private readonly base: Deferred<string>
|
|
542
555
|
private readonly path: string
|
|
543
556
|
private readonly getHeaders: HeadersProvider
|
|
544
557
|
private readonly onUnauthorized: UnauthorizedHandler | undefined
|
|
@@ -553,7 +566,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
553
566
|
private returning = false
|
|
554
567
|
|
|
555
568
|
constructor(
|
|
556
|
-
baseUrl: string
|
|
569
|
+
baseUrl: Deferred<string>,
|
|
557
570
|
path: string,
|
|
558
571
|
headers: Record<string, string> | HeadersProvider,
|
|
559
572
|
method: HttpMethod,
|
|
@@ -563,7 +576,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
563
576
|
transport: RequestTransport = plainFetch,
|
|
564
577
|
) {
|
|
565
578
|
super()
|
|
566
|
-
this.
|
|
579
|
+
this.base = baseUrl
|
|
567
580
|
this.path = path
|
|
568
581
|
this.getHeaders = asHeadersProvider(headers)
|
|
569
582
|
this.onUnauthorized = onUnauthorized
|
|
@@ -607,7 +620,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
607
620
|
|
|
608
621
|
async single(this: MutationBuilder<TRow, TTables, TName, TRow[]>): Promise<QueryResult<TRow>> {
|
|
609
622
|
if (!this.returning) return rowNotSelected()
|
|
610
|
-
|
|
623
|
+
// No `count` from the response: a success here is exactly one row, so it reports 1.
|
|
624
|
+
const { data, error, meta } = await this._execute({
|
|
611
625
|
Accept: "application/vnd.pgrst.object+json",
|
|
612
626
|
})
|
|
613
627
|
if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
|
|
@@ -655,6 +669,11 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
655
669
|
}
|
|
656
670
|
}
|
|
657
671
|
|
|
672
|
+
/** The address, read now: a deferred one is only known when the request is sent. */
|
|
673
|
+
private get baseUrl(): string {
|
|
674
|
+
return settle(this.base)
|
|
675
|
+
}
|
|
676
|
+
|
|
658
677
|
private async _execute(fetchHeaders: Record<string, string> = {}): Promise<QueryResult<TRow[]>> {
|
|
659
678
|
if (this.refusal !== undefined) return { data: null, error: this.refusal, count: null }
|
|
660
679
|
if (this.createThrough !== undefined) return this.createDraftRecords(this.createThrough)
|
|
@@ -748,7 +767,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
748
767
|
if (!this.returning) return this.nothingReturned()
|
|
749
768
|
const select = readBackColumns(this.params.get("select"), target.primaryKey, keys.length)
|
|
750
769
|
const result = await new QueryBuilder<Record<string, unknown>>(
|
|
751
|
-
this.
|
|
770
|
+
this.base,
|
|
752
771
|
this.path,
|
|
753
772
|
this.getHeaders,
|
|
754
773
|
select,
|
|
@@ -779,7 +798,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
779
798
|
const table = body["model_table"]
|
|
780
799
|
if (!res.ok) return readRefusal(res, `[supatype:mutation] ${fn} failed`, async () => ({ url, table }))
|
|
781
800
|
const answer: unknown = await res.json().catch(() => null)
|
|
782
|
-
return createdKeys(answer) ?? { message: `${fn} answered without the record ids`, status: res.status }
|
|
801
|
+
return createdKeys(answer) ?? new SupatypeError({ message: `${fn} answered without the record ids`, status: res.status })
|
|
783
802
|
}
|
|
784
803
|
}
|
|
785
804
|
|