@supatype/client 0.3.6 → 0.8.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 +69 -30
- 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 +86 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +383 -275
- 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 +170 -165
- 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 +57 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +300 -88
- 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 +137 -38
- 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 +98 -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 +434 -281
- 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 +289 -208
- 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 +333 -90
- package/src/select-types.ts +184 -0
- package/src/storage.ts +223 -44
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +104 -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 +187 -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 +142 -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-ack-ref.test.ts +112 -0
- 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-shared-channel.test.ts +209 -0
- 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 +187 -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 +7 -9
- 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 +17 -31
- package/tests/storage-url-encoding.test.ts +52 -0
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/blob.ts +10 -0
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +41 -14
- 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
package/src/index.ts
CHANGED
|
@@ -1,13 +1,26 @@
|
|
|
1
1
|
import { AuthClient } from "./auth.js"
|
|
2
2
|
import { onIdentityChange } from "./identity.js"
|
|
3
3
|
import { PreviewCredential } from "./preview.js"
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
QueryBuilder,
|
|
6
|
+
MutationBuilder,
|
|
7
|
+
fetchWithOptional401Retry,
|
|
8
|
+
type DraftCreate,
|
|
9
|
+
type HeadersProvider,
|
|
10
|
+
} from "./query.js"
|
|
11
|
+
import { registeredDraftModel } from "./draft-models-registry.js"
|
|
12
|
+
import { GENERATED_CLIENT_IMPORT } from "./generated-client.js"
|
|
13
|
+
import type { FetchOptions, RequestTransport } from "./fetch-with-retry.js"
|
|
5
14
|
import { defaultQueryCache, type QueryCache } from "./query-cache.js"
|
|
6
15
|
import { StorageClient } from "./storage.js"
|
|
7
16
|
import { RealtimeClient } from "./realtime.js"
|
|
8
|
-
import type {
|
|
9
|
-
import {
|
|
17
|
+
import type { RealtimePayload } from "./realtime.js"
|
|
18
|
+
import { subscribeToTable, type TableSubscribeOptions, type TableSubscription } from "./table-subscription.js"
|
|
19
|
+
import { PostgrestError, transportFailure } from "./errors.js"
|
|
10
20
|
import { createRetryFetch } from "./retry.js"
|
|
21
|
+
import { isJsonObject, isString, readJsonObject, refusalText } from "./json.js"
|
|
22
|
+
import { jwtRole } from "./jwt.js"
|
|
23
|
+
import { createGraphqlRunner } from "./graphql-transport.js"
|
|
11
24
|
import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
|
|
12
25
|
import type {
|
|
13
26
|
AnyDatabase,
|
|
@@ -19,7 +32,11 @@ import type {
|
|
|
19
32
|
SupatypeError,
|
|
20
33
|
RpcOptions,
|
|
21
34
|
SelectQueryOptions,
|
|
35
|
+
TableDef,
|
|
36
|
+
UpdateOptions,
|
|
22
37
|
} from "./types.js"
|
|
38
|
+
import type { MutationOptions } from "./query.js"
|
|
39
|
+
import type { SelectRow } from "./select-types.js"
|
|
23
40
|
import { DRAFT_SCHEMA } from "./types.js"
|
|
24
41
|
|
|
25
42
|
export type {
|
|
@@ -28,6 +45,7 @@ export type {
|
|
|
28
45
|
AuthChangeEvent,
|
|
29
46
|
AuthFlowType,
|
|
30
47
|
SupatypeError,
|
|
48
|
+
AuthRedirectError,
|
|
31
49
|
QueryResult,
|
|
32
50
|
MaskedField,
|
|
33
51
|
RpcResult,
|
|
@@ -45,13 +63,16 @@ export type {
|
|
|
45
63
|
SupatypeBuckets,
|
|
46
64
|
SupatypeFunctions,
|
|
47
65
|
AugmentedDatabase,
|
|
66
|
+
DraftUpdateOptions,
|
|
67
|
+
UpdateOptions,
|
|
48
68
|
} from "./types.js"
|
|
49
69
|
export {
|
|
50
70
|
generateCodeVerifier,
|
|
51
71
|
createCodeChallengeS256,
|
|
52
72
|
PKCE_METHOD_S256,
|
|
53
73
|
} from "./pkce.js"
|
|
54
|
-
export { DRAFT_SCHEMA } from "./types.js"
|
|
74
|
+
export { DRAFT_SCHEMA, PUBLISHING_SCHEMA } from "./types.js"
|
|
75
|
+
export type { SelectRow, SelectError, TableRelationship } from "./select-types.js"
|
|
55
76
|
|
|
56
77
|
/**
|
|
57
78
|
* A client whose database type the holder does not know.
|
|
@@ -70,15 +91,17 @@ export type AnyClient = SupatypeClient<AnyDatabase>
|
|
|
70
91
|
export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
71
92
|
export { AuthClient } from "./auth.js"
|
|
72
93
|
export { onIdentityChange, type IdentitySource } from "./identity.js"
|
|
73
|
-
export { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
|
|
94
|
+
export { QueryBuilder, MutationBuilder, type HeadersProvider, type RequestTransport } from "./query.js"
|
|
74
95
|
export { QueryCache, defaultQueryCache } from "./query-cache.js"
|
|
75
96
|
export { StorageClient, BucketClient } from "./storage.js"
|
|
76
|
-
export type { StorageObject, TransformOptions } from "./storage.js"
|
|
97
|
+
export type { StorageObject, StorageFolder, StorageListEntry, ListOptions, RemovedObject, StorageReference, TransformOptions } from "./storage.js"
|
|
77
98
|
export { RealtimeClient } from "./realtime.js"
|
|
78
99
|
export type { RealtimeEvent, RealtimePayload, ChannelStatus, PresenceEntry } from "./realtime.js"
|
|
100
|
+
// The bindings' shared subscription helpers are on `@supatype/client/bindings`, not here.
|
|
101
|
+
export type { TableSubscribeOptions, TableSubscription } from "./table-subscription.js"
|
|
79
102
|
export * from "./errors.js"
|
|
80
103
|
|
|
81
|
-
// Called by the generated `supatype/client.ts`, which is how a project tells the client which
|
|
104
|
+
// Called by the generated `supatype/generated/client.ts`, which is how a project tells the client which
|
|
82
105
|
// columns hold values a JSON parser would destroy. Exported because generated code imports it;
|
|
83
106
|
// applications do not call it.
|
|
84
107
|
export {
|
|
@@ -86,7 +109,17 @@ export {
|
|
|
86
109
|
fieldKindsAreRegistered,
|
|
87
110
|
forgetRegisteredFieldKinds,
|
|
88
111
|
type FieldKindsDocument,
|
|
112
|
+
type UnrecognisedFieldKindsDocument,
|
|
89
113
|
} from "./field-kinds-registry.js"
|
|
114
|
+
// Also called by the generated file: which tables keep drafts, so `insert` creates their records
|
|
115
|
+
// through `supatype.create_record`.
|
|
116
|
+
export {
|
|
117
|
+
registerDraftModels,
|
|
118
|
+
forgetRegisteredDraftModels,
|
|
119
|
+
type DraftModel,
|
|
120
|
+
type DraftModelsDocument,
|
|
121
|
+
type UnrecognisedDraftModelsDocument,
|
|
122
|
+
} from "./draft-models-registry.js"
|
|
90
123
|
export { fetchWithRetry, detectServerlessEnvironment, warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
|
|
91
124
|
export type { FetchOptions, ServerlessDetectionResult } from "./fetch-with-retry.js"
|
|
92
125
|
export { createRetryFetch } from "./retry.js"
|
|
@@ -96,37 +129,45 @@ export type { ErrorCodeEntry } from "./error-codes-doc.js"
|
|
|
96
129
|
export { CONNECTION_MODES, SERVERLESS_CONNECTION_WARNING, CONNECTION_FAQ } from "./serverless-docs.js"
|
|
97
130
|
export type { ConnectionModeDoc } from "./serverless-docs.js"
|
|
98
131
|
export { PreviewLinkError } from "./preview.js"
|
|
132
|
+
// pg_graphql sends its `JSON` scalar as a string and `graphql()` decodes it. These let another
|
|
133
|
+
// GraphQL client decode the same way with the schema it reads, and Studio's explorer run its
|
|
134
|
+
// send-as requests through the same runner.
|
|
135
|
+
export {
|
|
136
|
+
GRAPHQL_SCHEMA_QUERY,
|
|
137
|
+
GraphqlSchemaCache,
|
|
138
|
+
decodeGraphqlJsonFields,
|
|
139
|
+
readGraphqlSchema,
|
|
140
|
+
type GraphqlJsonDecoding,
|
|
141
|
+
type GraphqlSchema,
|
|
142
|
+
} from "./graphql-json.js"
|
|
143
|
+
export { createGraphqlRunner, type GraphqlTransport } from "./graphql-transport.js"
|
|
99
144
|
|
|
100
145
|
// ─── Table client ─────────────────────────────────────────────────────────────
|
|
101
146
|
|
|
102
|
-
interface TableDef {
|
|
103
|
-
Row: Record<string, unknown>
|
|
104
|
-
Insert: Record<string, unknown>
|
|
105
|
-
Update: Record<string, unknown>
|
|
106
|
-
}
|
|
107
|
-
|
|
108
147
|
/**
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
* Module-wide rather than per client because it only has to be unique, and a name never seen by
|
|
112
|
-
* one client cannot collide on another.
|
|
148
|
+
* One table, typed by its definition and by every table beside it: an embedded select is resolved
|
|
149
|
+
* against the other tables' rows and the relationships between them.
|
|
113
150
|
*/
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
151
|
+
class TableClient<
|
|
152
|
+
TDef extends TableDef,
|
|
153
|
+
TTables extends Record<string, TableDef> = Record<string, TableDef>,
|
|
154
|
+
TName extends string = string,
|
|
155
|
+
> {
|
|
117
156
|
private readonly baseUrl: string
|
|
118
157
|
private readonly table: string
|
|
119
158
|
private readonly path: string
|
|
120
159
|
private readonly getHeaders: HeadersProvider
|
|
121
160
|
private readonly onUnauthorized: (() => Promise<void>) | undefined
|
|
161
|
+
/** The client's retry-aware fetch, so `timeout` and `retry` reach table requests too. */
|
|
162
|
+
private readonly send: RequestTransport
|
|
122
163
|
private readonly queryCache: QueryCache
|
|
123
164
|
private readonly realtime: RealtimeClient
|
|
124
165
|
/**
|
|
125
166
|
* The schema this table's reads come from, set by `draft()`.
|
|
126
167
|
*
|
|
127
168
|
* Mutable, and safe to be: `from()` builds a fresh client per call, so nothing is shared between
|
|
128
|
-
* two queries. Reads only
|
|
129
|
-
*
|
|
169
|
+
* two queries. Reads only: a draft view is not writable, and `update` on a model with drafts
|
|
170
|
+
* saves a new version through the publishing functions instead.
|
|
130
171
|
*/
|
|
131
172
|
private profile: string | undefined
|
|
132
173
|
|
|
@@ -136,7 +177,8 @@ class TableClient<TDef extends TableDef> {
|
|
|
136
177
|
getHeaders: HeadersProvider,
|
|
137
178
|
realtime: RealtimeClient,
|
|
138
179
|
queryCache: QueryCache = defaultQueryCache,
|
|
139
|
-
onUnauthorized
|
|
180
|
+
onUnauthorized: (() => Promise<void>) | undefined,
|
|
181
|
+
send: RequestTransport,
|
|
140
182
|
) {
|
|
141
183
|
this.baseUrl = baseUrl
|
|
142
184
|
this.table = table
|
|
@@ -145,6 +187,7 @@ class TableClient<TDef extends TableDef> {
|
|
|
145
187
|
this.realtime = realtime
|
|
146
188
|
this.onUnauthorized = onUnauthorized
|
|
147
189
|
this.queryCache = queryCache
|
|
190
|
+
this.send = send
|
|
148
191
|
}
|
|
149
192
|
|
|
150
193
|
/**
|
|
@@ -161,15 +204,35 @@ class TableClient<TDef extends TableDef> {
|
|
|
161
204
|
* **Read-only, and permission is not the read rule.** A draft is visible to the record's creator
|
|
162
205
|
* and to the project's elevated Studio roles, or to a caller holding a signed preview link. A
|
|
163
206
|
* caller who may read published content is not thereby entitled to read what has not been
|
|
164
|
-
* published. Write with the ordinary `update`, which
|
|
165
|
-
* `
|
|
207
|
+
* published. Write with the ordinary `update`, which on a model with drafts saves a new draft of
|
|
208
|
+
* each record it matches and leaves the live rows alone; pass `{ publish: true }` to publish in the
|
|
209
|
+
* same call. A saved draft is published later by the generated `publish` database function in the
|
|
210
|
+
* `supatype` schema:
|
|
211
|
+
* `rpc("publish", { model_table: "posts", record_id: id }, { schema: "supatype" })`.
|
|
166
212
|
*/
|
|
167
213
|
draft(): this {
|
|
168
214
|
this.profile = DRAFT_SCHEMA
|
|
169
215
|
return this
|
|
170
216
|
}
|
|
171
217
|
|
|
172
|
-
|
|
218
|
+
/**
|
|
219
|
+
* Read rows, typed from the select string.
|
|
220
|
+
*
|
|
221
|
+
* `select("id, author:authors(name)")` resolves to `{ id: string; author: { name: string } | null }`
|
|
222
|
+
* from the generated schema: columns, aliases and embedded relations are read from the string, so
|
|
223
|
+
* the joined shape is not declared a second time by hand. See `select-types.ts` for the grammar.
|
|
224
|
+
* A string only known at run time types as the whole row.
|
|
225
|
+
*/
|
|
226
|
+
select<TColumns extends string = "*">(
|
|
227
|
+
columns?: TColumns | undefined,
|
|
228
|
+
options?: SelectQueryOptions | undefined,
|
|
229
|
+
): QueryBuilder<SelectRow<TTables, TName, TColumns>>
|
|
230
|
+
/** Read rows typed as `TResult`, for a shape the select string cannot describe. */
|
|
231
|
+
select<TResult>(
|
|
232
|
+
columns?: string | undefined,
|
|
233
|
+
options?: SelectQueryOptions | undefined,
|
|
234
|
+
): QueryBuilder<TResult>
|
|
235
|
+
select<TResult>(
|
|
173
236
|
columns?: string | undefined,
|
|
174
237
|
options?: SelectQueryOptions | undefined,
|
|
175
238
|
): QueryBuilder<TResult> {
|
|
@@ -183,27 +246,56 @@ class TableClient<TDef extends TableDef> {
|
|
|
183
246
|
// The profile joins the select options rather than riding a longer constructor: it is a
|
|
184
247
|
// property of the request being described, like `count` and `head` beside it.
|
|
185
248
|
{ ...options, ...(this.profile !== undefined && { profile: this.profile }) },
|
|
249
|
+
this.send,
|
|
186
250
|
)
|
|
187
251
|
}
|
|
188
252
|
|
|
253
|
+
/**
|
|
254
|
+
* Insert one row or several.
|
|
255
|
+
*
|
|
256
|
+
* **On a model that keeps drafts**, one record is created through `supatype.create_record`, as
|
|
257
|
+
* Studio creates it, and several through `supatype.create_records`, all or none in one call: each
|
|
258
|
+
* record starts as its first draft, and the rows come back read from the draft view in the shape
|
|
259
|
+
* and order a plain insert returns. A plain insert asking for the row back is refused there by a
|
|
260
|
+
* read rule that hides unpublished records, because Postgres checks the returned row against it
|
|
261
|
+
* before anything has made the new row visible to its author. The generated `supatype/generated/client.ts`
|
|
262
|
+
* says which models keep drafts; a client without it inserts as before.
|
|
263
|
+
*/
|
|
189
264
|
insert(
|
|
190
265
|
data: TDef["Insert"] | TDef["Insert"][],
|
|
191
|
-
): MutationBuilder<TDef["Row"]> {
|
|
192
|
-
return new MutationBuilder<TDef["Row"]>(
|
|
266
|
+
): MutationBuilder<TDef["Row"], TTables, TName> {
|
|
267
|
+
return new MutationBuilder<TDef["Row"], TTables, TName>(
|
|
193
268
|
this.baseUrl,
|
|
194
269
|
this.path,
|
|
195
270
|
this.getHeaders,
|
|
196
271
|
"POST",
|
|
197
272
|
data,
|
|
198
|
-
|
|
273
|
+
{ createThrough: this.draftCreate(data) },
|
|
199
274
|
this.onUnauthorized,
|
|
275
|
+
this.send,
|
|
200
276
|
)
|
|
201
277
|
}
|
|
202
278
|
|
|
279
|
+
/** Where an insert of `data` is created through the publishing functions: any rows, on a drafts model. */
|
|
280
|
+
private draftCreate(data: TDef["Insert"] | TDef["Insert"][]): DraftCreate | undefined {
|
|
281
|
+
const model = registeredDraftModel(this.table)
|
|
282
|
+
if (model === undefined) return undefined
|
|
283
|
+
// Nothing to create: the plain insert answers an empty array with no rows, as it always has.
|
|
284
|
+
if (Array.isArray(data) && data.length === 0) return undefined
|
|
285
|
+
return { table: this.table, primaryKey: model.primaryKey }
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Insert, or update the row a key or unique column already names.
|
|
290
|
+
*
|
|
291
|
+
* Never sent through `create_record`, on a drafts model or not: it cannot say what happens on a
|
|
292
|
+
* conflict, and an upsert that met an existing record would make a second one rather than update
|
|
293
|
+
* it. On a drafts model whose read rule hides unpublished records, create through `insert`.
|
|
294
|
+
*/
|
|
203
295
|
upsert(
|
|
204
296
|
data: TDef["Insert"] | TDef["Insert"][],
|
|
205
|
-
): MutationBuilder<TDef["Row"]> {
|
|
206
|
-
return new MutationBuilder<TDef["Row"]>(
|
|
297
|
+
): MutationBuilder<TDef["Row"], TTables, TName> {
|
|
298
|
+
return new MutationBuilder<TDef["Row"], TTables, TName>(
|
|
207
299
|
this.baseUrl,
|
|
208
300
|
this.path,
|
|
209
301
|
this.getHeaders,
|
|
@@ -211,23 +303,48 @@ class TableClient<TDef extends TableDef> {
|
|
|
211
303
|
data,
|
|
212
304
|
{ upsert: true },
|
|
213
305
|
this.onUnauthorized,
|
|
306
|
+
this.send,
|
|
214
307
|
)
|
|
215
308
|
}
|
|
216
309
|
|
|
217
|
-
|
|
218
|
-
|
|
310
|
+
/**
|
|
311
|
+
* Change the rows the filters match.
|
|
312
|
+
*
|
|
313
|
+
* **On a model that keeps drafts** the live rows do not change: each matched record gets a new
|
|
314
|
+
* draft through `supatype.save_drafts`, merged onto its newest version as Studio saves one, all or
|
|
315
|
+
* none in one call, and the drafts come back read from the draft view. Pass `{ publish: true }` to
|
|
316
|
+
* publish them in the same call, so the history records the version that went live. The generated
|
|
317
|
+
* `supatype/generated/client.ts` says which models keep drafts; elsewhere this is a plain `PATCH`, and
|
|
318
|
+
* `{ publish: true }` is refused, since there is nothing to publish.
|
|
319
|
+
*/
|
|
320
|
+
update(
|
|
321
|
+
data: TDef["Update"],
|
|
322
|
+
options?: UpdateOptions<TDef>,
|
|
323
|
+
): MutationBuilder<TDef["Row"], TTables, TName> {
|
|
324
|
+
return new MutationBuilder<TDef["Row"], TTables, TName>(
|
|
219
325
|
this.baseUrl,
|
|
220
326
|
this.path,
|
|
221
327
|
this.getHeaders,
|
|
222
328
|
"PATCH",
|
|
223
329
|
data,
|
|
224
|
-
|
|
330
|
+
this.draftEdit(options),
|
|
225
331
|
this.onUnauthorized,
|
|
332
|
+
this.send,
|
|
226
333
|
)
|
|
227
334
|
}
|
|
228
335
|
|
|
229
|
-
|
|
230
|
-
|
|
336
|
+
/** How an update is made: as drafts on a drafts model, else a plain `PATCH`, or refused. */
|
|
337
|
+
private draftEdit(options: unknown): MutationOptions | undefined {
|
|
338
|
+
const publish = isJsonObject(options) && options["publish"] === true
|
|
339
|
+
const model = registeredDraftModel(this.table)
|
|
340
|
+
if (model !== undefined) return { editThrough: { table: this.table, primaryKey: model.primaryKey, publish } }
|
|
341
|
+
if (!publish) return undefined
|
|
342
|
+
const message = `{ publish: true } applies to a model that keeps drafts, and "${this.table}" is not one this client knows of. Import the client from the generated ${GENERATED_CLIENT_IMPORT}, which says which models keep drafts.`
|
|
343
|
+
return { refusal: { message } }
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
delete(): MutationBuilder<TDef["Row"], TTables, TName> {
|
|
347
|
+
return new MutationBuilder<TDef["Row"], TTables, TName>(
|
|
231
348
|
this.baseUrl,
|
|
232
349
|
this.path,
|
|
233
350
|
this.getHeaders,
|
|
@@ -235,6 +352,7 @@ class TableClient<TDef extends TableDef> {
|
|
|
235
352
|
undefined,
|
|
236
353
|
undefined,
|
|
237
354
|
this.onUnauthorized,
|
|
355
|
+
this.send,
|
|
238
356
|
)
|
|
239
357
|
}
|
|
240
358
|
|
|
@@ -244,47 +362,14 @@ class TableClient<TDef extends TableDef> {
|
|
|
244
362
|
* Phase 10.6 F11: preferred over raw `client.realtime.channel(...)`. The returned `channel` is
|
|
245
363
|
* already subscribed; call `channel.subscribe(cb)` only to watch its status.
|
|
246
364
|
*
|
|
247
|
-
* Each call gets a channel of its own
|
|
248
|
-
*
|
|
249
|
-
* unsubscribe removed the channel out from under the second. The name still reads as
|
|
250
|
-
* `schema:table` to anything that splits it, which is what a server predating `table` in the
|
|
251
|
-
* subscribe frame falls back to.
|
|
365
|
+
* Each call gets a channel of its own; `subscribeToTable` says why. The framework bindings join
|
|
366
|
+
* through the same function, so a table subscribed either way behaves the same.
|
|
252
367
|
*/
|
|
253
368
|
subscribe(
|
|
254
369
|
callback: (payload: RealtimePayload<TDef["Row"]>) => void,
|
|
255
|
-
opts?:
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
schema?: string | undefined
|
|
259
|
-
} | undefined,
|
|
260
|
-
): {
|
|
261
|
-
unsubscribe: () => void
|
|
262
|
-
channel: ReturnType<RealtimeClient["channel"]>
|
|
263
|
-
} {
|
|
264
|
-
const event = opts?.event ?? "*"
|
|
265
|
-
const schema = opts?.schema ?? "public"
|
|
266
|
-
tableSubscriptionCount += 1
|
|
267
|
-
const channel = this.realtime
|
|
268
|
-
.channel(`${schema}:${this.table}:${tableSubscriptionCount}`)
|
|
269
|
-
.on(
|
|
270
|
-
"postgres_changes",
|
|
271
|
-
{
|
|
272
|
-
event,
|
|
273
|
-
schema,
|
|
274
|
-
table: this.table,
|
|
275
|
-
...(opts?.filter !== undefined && { filter: opts.filter }),
|
|
276
|
-
},
|
|
277
|
-
callback,
|
|
278
|
-
)
|
|
279
|
-
// `on()` only records the listener. Without this nothing opened a socket or sent the join,
|
|
280
|
-
// and the callback waited forever unless something else on the client had joined already.
|
|
281
|
-
.subscribe()
|
|
282
|
-
return {
|
|
283
|
-
channel,
|
|
284
|
-
unsubscribe: () => {
|
|
285
|
-
channel.unsubscribe()
|
|
286
|
-
},
|
|
287
|
-
}
|
|
370
|
+
opts?: TableSubscribeOptions | undefined,
|
|
371
|
+
): TableSubscription {
|
|
372
|
+
return subscribeToTable(this.realtime, this.table, callback, opts)
|
|
288
373
|
}
|
|
289
374
|
}
|
|
290
375
|
|
|
@@ -295,18 +380,30 @@ export interface GlobalClient<TRow extends Record<string, unknown> = Record<stri
|
|
|
295
380
|
update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }>
|
|
296
381
|
}
|
|
297
382
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
383
|
+
/**
|
|
384
|
+
* The boundary between a function's answer and the return type the generated schema declares.
|
|
385
|
+
*
|
|
386
|
+
* A database or edge function may answer with any JSON value (an edge function with text, too), so
|
|
387
|
+
* the only thing to check is that there is a value. That it has the declared type is the generated
|
|
388
|
+
* schema's claim about the function, which nothing on the client can check.
|
|
389
|
+
*/
|
|
390
|
+
function isDeclaredReturn<T>(value: unknown): value is T {
|
|
391
|
+
return value !== undefined
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* The message and machine-readable code on an edge function's error body. A handler may send its
|
|
396
|
+
* own `code`. The functions worker answers its own failures as `{ error: <code>, message }`, so
|
|
397
|
+
* `error` is a code when a `message` is beside it. On its own, `error` is a handler's sentence
|
|
398
|
+
* (`{ error: "Email already taken" }`) and is the message.
|
|
399
|
+
*/
|
|
400
|
+
function functionError(body: Record<string, unknown>, status: number): SupatypeError {
|
|
401
|
+
const workerCode = isString(body["message"]) ? body["error"] : undefined
|
|
402
|
+
const code = isString(body["code"]) ? body["code"] : isString(workerCode) ? workerCode : undefined
|
|
403
|
+
return {
|
|
404
|
+
message: refusalText(body) ?? `Function returned ${status}`,
|
|
405
|
+
status,
|
|
406
|
+
...(code !== undefined && { code }),
|
|
310
407
|
}
|
|
311
408
|
}
|
|
312
409
|
|
|
@@ -379,18 +476,26 @@ export interface FunctionInvokeOptions {
|
|
|
379
476
|
headers?: Record<string, string> | undefined
|
|
380
477
|
/** Request body (JSON-serialisable) */
|
|
381
478
|
body?: unknown | undefined
|
|
479
|
+
/**
|
|
480
|
+
* Retry this call on a transient failure although it is not a GET. Default: false.
|
|
481
|
+
*
|
|
482
|
+
* Only GET calls are retried otherwise: a POST that failed in flight may already have run the
|
|
483
|
+
* function, and running it again could charge a card or send an email twice. Set this when a
|
|
484
|
+
* second run is harmless.
|
|
485
|
+
*/
|
|
486
|
+
idempotent?: boolean | undefined
|
|
382
487
|
}
|
|
383
488
|
|
|
384
489
|
class FunctionsClient {
|
|
385
490
|
private readonly baseUrl: string
|
|
386
491
|
private readonly getHeaders: HeadersProvider
|
|
387
492
|
private readonly onUnauthorized: (() => Promise<void>) | undefined
|
|
388
|
-
private readonly doFetch:
|
|
493
|
+
private readonly doFetch: RequestTransport
|
|
389
494
|
|
|
390
495
|
constructor(
|
|
391
496
|
baseUrl: string,
|
|
392
497
|
getHeaders: HeadersProvider,
|
|
393
|
-
doFetch:
|
|
498
|
+
doFetch: RequestTransport,
|
|
394
499
|
onUnauthorized?: (() => Promise<void>) | undefined,
|
|
395
500
|
) {
|
|
396
501
|
this.baseUrl = baseUrl
|
|
@@ -420,8 +525,9 @@ class FunctionsClient {
|
|
|
420
525
|
...options?.headers,
|
|
421
526
|
})
|
|
422
527
|
|
|
423
|
-
const fetchOpts: RequestInit = {
|
|
528
|
+
const fetchOpts: RequestInit & FetchOptions = {
|
|
424
529
|
method,
|
|
530
|
+
...(options?.idempotent === true && { idempotent: true }),
|
|
425
531
|
}
|
|
426
532
|
|
|
427
533
|
if (options?.body !== undefined && method !== "GET") {
|
|
@@ -429,46 +535,24 @@ class FunctionsClient {
|
|
|
429
535
|
}
|
|
430
536
|
|
|
431
537
|
try {
|
|
432
|
-
|
|
433
|
-
|
|
538
|
+
const res = await fetchWithOptional401Retry(
|
|
539
|
+
this.doFetch,
|
|
434
540
|
`${this.baseUrl}/functions/v1/${functionName}`,
|
|
435
|
-
|
|
541
|
+
fetchOpts,
|
|
542
|
+
resolveHeaders,
|
|
543
|
+
this.onUnauthorized,
|
|
436
544
|
)
|
|
437
|
-
if (res.status === 401 && this.onUnauthorized !== undefined) {
|
|
438
|
-
await this.onUnauthorized()
|
|
439
|
-
headers = await resolveHeaders()
|
|
440
|
-
res = await this.doFetch(
|
|
441
|
-
`${this.baseUrl}/functions/v1/${functionName}`,
|
|
442
|
-
{ ...fetchOpts, headers },
|
|
443
|
-
)
|
|
444
|
-
}
|
|
445
545
|
|
|
446
546
|
if (!res.ok) {
|
|
447
|
-
|
|
448
|
-
return {
|
|
449
|
-
data: null,
|
|
450
|
-
error: {
|
|
451
|
-
message: typeof body["message"] === "string" ? body["message"] : `Function returned ${res.status}`,
|
|
452
|
-
status: res.status,
|
|
453
|
-
...(typeof body["code"] === "string" ? { code: body["code"] } : {}),
|
|
454
|
-
},
|
|
455
|
-
}
|
|
547
|
+
return { data: null, error: functionError(await readJsonObject(res), res.status) }
|
|
456
548
|
}
|
|
457
549
|
|
|
458
550
|
const contentType = res.headers.get("content-type") ?? ""
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
// Return text for non-JSON responses
|
|
465
|
-
const text = await res.text()
|
|
466
|
-
return { data: text as unknown as EdgeFunctionReturns<TFn>, error: null }
|
|
551
|
+
// Text for a response that is not JSON.
|
|
552
|
+
const data = contentType.includes("application/json") ? await res.json() : await res.text()
|
|
553
|
+
return { data: isDeclaredReturn<EdgeFunctionReturns<TFn>>(data) ? data : null, error: null }
|
|
467
554
|
} catch (e) {
|
|
468
|
-
return {
|
|
469
|
-
data: null,
|
|
470
|
-
error: { message: e instanceof Error ? e.message : "Network error" },
|
|
471
|
-
}
|
|
555
|
+
return { data: null, error: transportFailure(e) }
|
|
472
556
|
}
|
|
473
557
|
}
|
|
474
558
|
}
|
|
@@ -479,16 +563,26 @@ export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabas
|
|
|
479
563
|
serviceRoleKey: string | undefined
|
|
480
564
|
from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
|
|
481
565
|
table: TTable,
|
|
482
|
-
): TableClient<TDatabase["public"]["Tables"][TTable]>
|
|
566
|
+
): TableClient<TDatabase["public"]["Tables"][TTable], TDatabase["public"]["Tables"], TTable>
|
|
483
567
|
global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow>
|
|
484
568
|
auth: AuthClient
|
|
485
569
|
storage: StorageClient
|
|
486
570
|
realtime: RealtimeClient
|
|
487
571
|
functions: FunctionsClient
|
|
488
|
-
|
|
572
|
+
/**
|
|
573
|
+
* Run a GraphQL query. `options.idempotent`: retry on a transient failure, for a query that is not
|
|
574
|
+
* a mutation.
|
|
575
|
+
*
|
|
576
|
+
* Rich text, blocks and json fields come back as values, not as the JSON strings pg_graphql sends:
|
|
577
|
+
* the client reads the schema once and decodes every field typed with its `JSON` scalar, through
|
|
578
|
+
* aliases, fragments, relations and lists. `TData` names the answer's shape, typically from
|
|
579
|
+
* `TableRow<"post">`; nothing checks it at runtime.
|
|
580
|
+
*/
|
|
581
|
+
graphql<TData = unknown>(
|
|
489
582
|
query: string,
|
|
490
583
|
variables?: Record<string, unknown> | undefined,
|
|
491
|
-
|
|
584
|
+
options?: { idempotent?: boolean | undefined } | undefined,
|
|
585
|
+
): Promise<{ data: TData | null; error: SupatypeError | null }>
|
|
492
586
|
/**
|
|
493
587
|
* Call a Postgres function via PostgREST's `/rpc/function_name` endpoint.
|
|
494
588
|
*
|
|
@@ -533,11 +627,16 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
533
627
|
? null
|
|
534
628
|
: new PreviewCredential(config.url, config.previewCode)
|
|
535
629
|
|
|
630
|
+
// `headers` may be a function, read on every request: Studio changes the acting mode it asks for
|
|
631
|
+
// without rebuilding its client (and losing its session and sockets).
|
|
632
|
+
const extraHeaders = (): Record<string, string> =>
|
|
633
|
+
typeof config.headers === "function" ? config.headers() : (config.headers ?? {})
|
|
634
|
+
|
|
536
635
|
const baseHeaders: Record<string, string> = {
|
|
537
636
|
apikey: config.anonKey,
|
|
538
637
|
Authorization: `Bearer ${config.anonKey}`,
|
|
539
638
|
"Content-Type": "application/json",
|
|
540
|
-
...
|
|
639
|
+
...extraHeaders(),
|
|
541
640
|
}
|
|
542
641
|
|
|
543
642
|
// Create a retry-aware fetch bound to client-level config
|
|
@@ -549,13 +648,17 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
549
648
|
const auth = new AuthClient(`${config.url}/auth/v1`, baseHeaders, {
|
|
550
649
|
initialSession: config.initialSession,
|
|
551
650
|
persistSession: config.auth?.persistSession,
|
|
651
|
+
autoRefreshToken: config.auth?.autoRefreshToken,
|
|
652
|
+
refreshExpiredToken: config.auth?.refreshExpiredToken,
|
|
552
653
|
storageKey: config.auth?.storageKey,
|
|
553
654
|
cookiePrefix: config.auth?.cookiePrefix,
|
|
554
655
|
storage: config.auth?.storage,
|
|
656
|
+
detectSessionInUrl: config.auth?.detectSessionInUrl,
|
|
657
|
+
transport: doFetch,
|
|
555
658
|
})
|
|
556
659
|
const queryCache = config.queryCache ?? defaultQueryCache
|
|
557
660
|
|
|
558
|
-
const
|
|
661
|
+
const credentialHeaders = async (): Promise<Record<string, string>> => {
|
|
559
662
|
// Studio and other admin tools pass serviceRoleKey, use it for table/RPC/GraphQL
|
|
560
663
|
// so supatype_admin RLS policies and bypass rules apply (anon would fail).
|
|
561
664
|
if (config.serviceRoleKey) {
|
|
@@ -563,7 +666,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
563
666
|
apikey: config.serviceRoleKey,
|
|
564
667
|
Authorization: `Bearer ${config.serviceRoleKey}`,
|
|
565
668
|
"Content-Type": "application/json",
|
|
566
|
-
...
|
|
669
|
+
...extraHeaders(),
|
|
567
670
|
}
|
|
568
671
|
}
|
|
569
672
|
// A preview link is the whole credential, and it comes before any session on purpose: whoever
|
|
@@ -587,13 +690,19 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
587
690
|
return baseHeaders
|
|
588
691
|
}
|
|
589
692
|
|
|
693
|
+
// Every request's headers: its credential, then the caller's own extra headers as they are now.
|
|
694
|
+
const getAuthHeaders = async (): Promise<Record<string, string>> => ({
|
|
695
|
+
...(await credentialHeaders()),
|
|
696
|
+
...extraHeaders(),
|
|
697
|
+
})
|
|
698
|
+
|
|
590
699
|
// Storage asks for headers per request, like every other client here.
|
|
591
700
|
//
|
|
592
701
|
// It used to be handed a plain object built above, before anybody had signed in, so every storage
|
|
593
702
|
// request carried the anon key for the life of the page. An app's per-user storage policies saw
|
|
594
703
|
// `anon` rather than the caller, and through Studio's proxy the request was refused outright,
|
|
595
704
|
// because an anon key carries no `sub` and the proxy requires one.
|
|
596
|
-
const storage = new StorageClient(`${config.url}/storage/v1`, getAuthHeaders)
|
|
705
|
+
const storage = new StorageClient(`${config.url}/storage/v1`, getAuthHeaders, doFetch)
|
|
597
706
|
|
|
598
707
|
// The same provider the other sub-clients get, not `baseHeaders`.
|
|
599
708
|
//
|
|
@@ -608,6 +717,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
608
717
|
: (): Promise<void> => auth.ensureValidSession()
|
|
609
718
|
|
|
610
719
|
const functions = new FunctionsClient(config.url, getAuthHeaders, doFetch, onUnauthorized)
|
|
720
|
+
const runGraphql = createGraphqlRunner({ endpoint: `${config.url}/graphql/v1`, send: doFetch, headers: getAuthHeaders, onUnauthorized })
|
|
611
721
|
|
|
612
722
|
// Signing in has to reach an already-open socket.
|
|
613
723
|
//
|
|
@@ -626,30 +736,39 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
626
736
|
void realtime.reauthenticate()
|
|
627
737
|
})
|
|
628
738
|
|
|
739
|
+
// One place that wires a table to this client's headers, cache, auth refresh and fetch.
|
|
740
|
+
const tableClient = <
|
|
741
|
+
TDef extends TableDef,
|
|
742
|
+
TTables extends Record<string, TableDef> = Record<string, TableDef>,
|
|
743
|
+
TName extends string = string,
|
|
744
|
+
>(table: string): TableClient<TDef, TTables, TName> =>
|
|
745
|
+
new TableClient<TDef, TTables, TName>(config.url, table, getAuthHeaders, realtime, queryCache, onUnauthorized, doFetch)
|
|
746
|
+
|
|
629
747
|
return {
|
|
630
748
|
url: config.url,
|
|
631
749
|
serviceRoleKey: config.serviceRoleKey,
|
|
632
750
|
|
|
633
751
|
from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
|
|
634
752
|
table: TTable,
|
|
635
|
-
): TableClient<TDatabase["public"]["Tables"][TTable]> {
|
|
753
|
+
): TableClient<TDatabase["public"]["Tables"][TTable], TDatabase["public"]["Tables"], TTable> {
|
|
636
754
|
type TDef = TDatabase["public"]["Tables"][TTable]
|
|
637
|
-
return
|
|
755
|
+
return tableClient<TDef, TDatabase["public"]["Tables"], TTable>(table)
|
|
638
756
|
},
|
|
639
757
|
|
|
640
758
|
global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow> {
|
|
641
759
|
const tableName = `_global_${name}`
|
|
642
|
-
|
|
760
|
+
// A global is one row that always exists, so a write to it names only the fields it changes.
|
|
761
|
+
type TDef = { Row: TRow; Insert: Partial<TRow>; Update: Partial<TRow> }
|
|
643
762
|
return {
|
|
644
763
|
async get(): Promise<{ data: TRow | null; error: SupatypeError | null }> {
|
|
645
|
-
const tc =
|
|
764
|
+
const tc = tableClient<TDef, Record<string, TDef>>(tableName)
|
|
646
765
|
const result = await tc.select().limit(1).maybeSingle()
|
|
647
766
|
return { data: result.data ?? null, error: result.error }
|
|
648
767
|
},
|
|
649
768
|
async update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }> {
|
|
650
|
-
const tc =
|
|
651
|
-
const result = await tc.upsert(data
|
|
652
|
-
const row =
|
|
769
|
+
const tc = tableClient<TDef>(tableName)
|
|
770
|
+
const result = await tc.upsert(data)
|
|
771
|
+
const row = result.data?.[0] ?? null
|
|
653
772
|
return { data: row, error: result.error }
|
|
654
773
|
},
|
|
655
774
|
}
|
|
@@ -660,50 +779,17 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
660
779
|
realtime,
|
|
661
780
|
functions,
|
|
662
781
|
|
|
663
|
-
|
|
782
|
+
/**
|
|
783
|
+
* Run a GraphQL query. Sent as a POST, so it is not retried unless `options.idempotent` says a
|
|
784
|
+
* second copy is harmless, as it is for any query that is not a mutation.
|
|
785
|
+
*/
|
|
786
|
+
async graphql<TData = unknown>(
|
|
664
787
|
query: string,
|
|
665
788
|
variables?: Record<string, unknown> | undefined,
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
}
|
|
671
|
-
let res: Response
|
|
672
|
-
try {
|
|
673
|
-
res = await doFetch(`${config.url}/graphql/v1`, {
|
|
674
|
-
method: "POST",
|
|
675
|
-
headers: await getAuthHeaders(),
|
|
676
|
-
body: JSON.stringify(body),
|
|
677
|
-
})
|
|
678
|
-
if (res.status === 401 && onUnauthorized !== undefined) {
|
|
679
|
-
await onUnauthorized()
|
|
680
|
-
res = await doFetch(`${config.url}/graphql/v1`, {
|
|
681
|
-
method: "POST",
|
|
682
|
-
headers: await getAuthHeaders(),
|
|
683
|
-
body: JSON.stringify(body),
|
|
684
|
-
})
|
|
685
|
-
}
|
|
686
|
-
} catch (e) {
|
|
687
|
-
return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
|
|
688
|
-
}
|
|
689
|
-
let json: Record<string, unknown>
|
|
690
|
-
try {
|
|
691
|
-
json = await res.json() as Record<string, unknown>
|
|
692
|
-
} catch {
|
|
693
|
-
return { data: null, error: { message: `GraphQL endpoint returned a non-JSON response (HTTP ${res.status} ${res.statusText})` } }
|
|
694
|
-
}
|
|
695
|
-
if (!res.ok) {
|
|
696
|
-
const message =
|
|
697
|
-
typeof json["message"] === "string" ? json["message"]
|
|
698
|
-
: typeof json["error"] === "string" ? json["error"]
|
|
699
|
-
: `GraphQL request failed (HTTP ${res.status})`
|
|
700
|
-
return { data: json["data"] ?? null, error: { message, status: res.status } }
|
|
701
|
-
}
|
|
702
|
-
if (json["errors"] !== undefined) {
|
|
703
|
-
const errors = json["errors"] as Array<{ message: string }>
|
|
704
|
-
return { data: json["data"] ?? null, error: { message: (errors[0]?.message ?? "GraphQL error") } }
|
|
705
|
-
}
|
|
706
|
-
return { data: json["data"] ?? null, error: null }
|
|
789
|
+
options?: { idempotent?: boolean | undefined } | undefined,
|
|
790
|
+
): Promise<{ data: TData | null; error: SupatypeError | null }> {
|
|
791
|
+
const { data, error } = await runGraphql(query, variables, options)
|
|
792
|
+
return { data: isDeclaredReturn<TData>(data) ? data : null, error }
|
|
707
793
|
},
|
|
708
794
|
|
|
709
795
|
async rpc<TFn extends FunctionNames<TDatabase>>(
|
|
@@ -711,47 +797,40 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
711
797
|
params?: FunctionArgs<TDatabase, TFn> | undefined,
|
|
712
798
|
options?: RpcOptions | undefined,
|
|
713
799
|
): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>> {
|
|
714
|
-
const headers: Record<string, string> = { ...(await getAuthHeaders()) }
|
|
715
800
|
const method = options?.head === true ? "HEAD" : "POST"
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
}
|
|
801
|
+
// Resolved per attempt, so the resend after a 401 carries the same `Prefer` and profile as
|
|
802
|
+
// the first send. It used to rebuild only `Prefer` and drop the schema.
|
|
803
|
+
const rpcHeaders = async (): Promise<Record<string, string>> => ({
|
|
804
|
+
...(await getAuthHeaders()),
|
|
805
|
+
...(options?.count !== undefined && { Prefer: `count=${options.count}` }),
|
|
806
|
+
// PostgREST resolves `/rpc/<name>` against the default profile, so a function in any other
|
|
807
|
+
// schema is unreachable without this. `Content-Profile` rather than `Accept-Profile`,
|
|
808
|
+
// because an RPC call is a POST and PostgREST reads the write-side header for it.
|
|
809
|
+
...(options?.schema !== undefined && { "Content-Profile": options.schema }),
|
|
810
|
+
})
|
|
726
811
|
|
|
727
812
|
let res: Response
|
|
728
813
|
try {
|
|
729
|
-
res = await
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
})
|
|
734
|
-
if (res.status === 401 && onUnauthorized !== undefined) {
|
|
735
|
-
await onUnauthorized()
|
|
736
|
-
const retryHeaders: Record<string, string> = { ...(await getAuthHeaders()) }
|
|
737
|
-
if (options?.count !== undefined) {
|
|
738
|
-
retryHeaders["Prefer"] = `count=${options.count}`
|
|
739
|
-
}
|
|
740
|
-
res = await doFetch(`${config.url}/rest/v1/rpc/${fn}`, {
|
|
814
|
+
res = await fetchWithOptional401Retry(
|
|
815
|
+
doFetch,
|
|
816
|
+
`${config.url}/rest/v1/rpc/${fn}`,
|
|
817
|
+
{
|
|
741
818
|
method,
|
|
742
|
-
headers: retryHeaders,
|
|
743
819
|
...(params !== undefined && method !== "HEAD" && { body: JSON.stringify(params) }),
|
|
744
|
-
|
|
745
|
-
|
|
820
|
+
...(options?.idempotent === true && { idempotent: true }),
|
|
821
|
+
},
|
|
822
|
+
rpcHeaders,
|
|
823
|
+
onUnauthorized,
|
|
824
|
+
)
|
|
746
825
|
} catch (e) {
|
|
747
|
-
return { data: null, error:
|
|
826
|
+
return { data: null, error: transportFailure(e) }
|
|
748
827
|
}
|
|
749
828
|
|
|
750
829
|
if (!res.ok) {
|
|
751
|
-
const body = await res
|
|
830
|
+
const body = await readJsonObject(res)
|
|
752
831
|
const pgError = PostgrestError.fromResponse(
|
|
753
832
|
{
|
|
754
|
-
message:
|
|
833
|
+
message: refusalText(body),
|
|
755
834
|
code: typeof body["code"] === "string" ? body["code"] : undefined,
|
|
756
835
|
details: typeof body["details"] === "string" ? body["details"] : undefined,
|
|
757
836
|
hint: typeof body["hint"] === "string" ? body["hint"] : undefined,
|
|
@@ -764,6 +843,8 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
764
843
|
message: pgError.message,
|
|
765
844
|
status: pgError.statusCode,
|
|
766
845
|
code: pgError.code,
|
|
846
|
+
...(pgError.hint !== null && pgError.hint !== "" && { hint: pgError.hint }),
|
|
847
|
+
...(pgError.details !== null && pgError.details !== "" && { details: pgError.details }),
|
|
767
848
|
},
|
|
768
849
|
}
|
|
769
850
|
}
|
|
@@ -772,8 +853,8 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
772
853
|
return { data: null, error: null }
|
|
773
854
|
}
|
|
774
855
|
|
|
775
|
-
const data = await res.json()
|
|
776
|
-
return { data, error: null }
|
|
856
|
+
const data = await res.json()
|
|
857
|
+
return { data: isDeclaredReturn<FunctionReturns<TDatabase, TFn>>(data) ? data : null, error: null }
|
|
777
858
|
},
|
|
778
859
|
}
|
|
779
860
|
}
|