@supatype/client 0.3.5 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +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
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, 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,19 +380,15 @@ 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
|
-
return typeof payload["role"] === "string" ? payload["role"] : null
|
|
308
|
-
} catch {
|
|
309
|
-
return null
|
|
310
|
-
}
|
|
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
|
|
311
392
|
}
|
|
312
393
|
|
|
313
394
|
/**
|
|
@@ -379,18 +460,26 @@ export interface FunctionInvokeOptions {
|
|
|
379
460
|
headers?: Record<string, string> | undefined
|
|
380
461
|
/** Request body (JSON-serialisable) */
|
|
381
462
|
body?: unknown | undefined
|
|
463
|
+
/**
|
|
464
|
+
* Retry this call on a transient failure although it is not a GET. Default: false.
|
|
465
|
+
*
|
|
466
|
+
* Only GET calls are retried otherwise: a POST that failed in flight may already have run the
|
|
467
|
+
* function, and running it again could charge a card or send an email twice. Set this when a
|
|
468
|
+
* second run is harmless.
|
|
469
|
+
*/
|
|
470
|
+
idempotent?: boolean | undefined
|
|
382
471
|
}
|
|
383
472
|
|
|
384
473
|
class FunctionsClient {
|
|
385
474
|
private readonly baseUrl: string
|
|
386
475
|
private readonly getHeaders: HeadersProvider
|
|
387
476
|
private readonly onUnauthorized: (() => Promise<void>) | undefined
|
|
388
|
-
private readonly doFetch:
|
|
477
|
+
private readonly doFetch: RequestTransport
|
|
389
478
|
|
|
390
479
|
constructor(
|
|
391
480
|
baseUrl: string,
|
|
392
481
|
getHeaders: HeadersProvider,
|
|
393
|
-
doFetch:
|
|
482
|
+
doFetch: RequestTransport,
|
|
394
483
|
onUnauthorized?: (() => Promise<void>) | undefined,
|
|
395
484
|
) {
|
|
396
485
|
this.baseUrl = baseUrl
|
|
@@ -420,8 +509,9 @@ class FunctionsClient {
|
|
|
420
509
|
...options?.headers,
|
|
421
510
|
})
|
|
422
511
|
|
|
423
|
-
const fetchOpts: RequestInit = {
|
|
512
|
+
const fetchOpts: RequestInit & FetchOptions = {
|
|
424
513
|
method,
|
|
514
|
+
...(options?.idempotent === true && { idempotent: true }),
|
|
425
515
|
}
|
|
426
516
|
|
|
427
517
|
if (options?.body !== undefined && method !== "GET") {
|
|
@@ -429,22 +519,16 @@ class FunctionsClient {
|
|
|
429
519
|
}
|
|
430
520
|
|
|
431
521
|
try {
|
|
432
|
-
|
|
433
|
-
|
|
522
|
+
const res = await fetchWithOptional401Retry(
|
|
523
|
+
this.doFetch,
|
|
434
524
|
`${this.baseUrl}/functions/v1/${functionName}`,
|
|
435
|
-
|
|
525
|
+
fetchOpts,
|
|
526
|
+
resolveHeaders,
|
|
527
|
+
this.onUnauthorized,
|
|
436
528
|
)
|
|
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
529
|
|
|
446
530
|
if (!res.ok) {
|
|
447
|
-
const body = await res
|
|
531
|
+
const body = await readJsonObject(res)
|
|
448
532
|
return {
|
|
449
533
|
data: null,
|
|
450
534
|
error: {
|
|
@@ -456,19 +540,11 @@ class FunctionsClient {
|
|
|
456
540
|
}
|
|
457
541
|
|
|
458
542
|
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 }
|
|
543
|
+
// Text for a response that is not JSON.
|
|
544
|
+
const data = contentType.includes("application/json") ? await res.json() : await res.text()
|
|
545
|
+
return { data: isDeclaredReturn<EdgeFunctionReturns<TFn>>(data) ? data : null, error: null }
|
|
467
546
|
} catch (e) {
|
|
468
|
-
return {
|
|
469
|
-
data: null,
|
|
470
|
-
error: { message: e instanceof Error ? e.message : "Network error" },
|
|
471
|
-
}
|
|
547
|
+
return { data: null, error: transportFailure(e) }
|
|
472
548
|
}
|
|
473
549
|
}
|
|
474
550
|
}
|
|
@@ -479,16 +555,26 @@ export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabas
|
|
|
479
555
|
serviceRoleKey: string | undefined
|
|
480
556
|
from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
|
|
481
557
|
table: TTable,
|
|
482
|
-
): TableClient<TDatabase["public"]["Tables"][TTable]>
|
|
558
|
+
): TableClient<TDatabase["public"]["Tables"][TTable], TDatabase["public"]["Tables"], TTable>
|
|
483
559
|
global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow>
|
|
484
560
|
auth: AuthClient
|
|
485
561
|
storage: StorageClient
|
|
486
562
|
realtime: RealtimeClient
|
|
487
563
|
functions: FunctionsClient
|
|
488
|
-
|
|
564
|
+
/**
|
|
565
|
+
* Run a GraphQL query. `options.idempotent`: retry on a transient failure, for a query that is not
|
|
566
|
+
* a mutation.
|
|
567
|
+
*
|
|
568
|
+
* Rich text, blocks and json fields come back as values, not as the JSON strings pg_graphql sends:
|
|
569
|
+
* the client reads the schema once and decodes every field typed with its `JSON` scalar, through
|
|
570
|
+
* aliases, fragments, relations and lists. `TData` names the answer's shape, typically from
|
|
571
|
+
* `TableRow<"post">`; nothing checks it at runtime.
|
|
572
|
+
*/
|
|
573
|
+
graphql<TData = unknown>(
|
|
489
574
|
query: string,
|
|
490
575
|
variables?: Record<string, unknown> | undefined,
|
|
491
|
-
|
|
576
|
+
options?: { idempotent?: boolean | undefined } | undefined,
|
|
577
|
+
): Promise<{ data: TData | null; error: SupatypeError | null }>
|
|
492
578
|
/**
|
|
493
579
|
* Call a Postgres function via PostgREST's `/rpc/function_name` endpoint.
|
|
494
580
|
*
|
|
@@ -533,11 +619,16 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
533
619
|
? null
|
|
534
620
|
: new PreviewCredential(config.url, config.previewCode)
|
|
535
621
|
|
|
622
|
+
// `headers` may be a function, read on every request: Studio changes the acting mode it asks for
|
|
623
|
+
// without rebuilding its client (and losing its session and sockets).
|
|
624
|
+
const extraHeaders = (): Record<string, string> =>
|
|
625
|
+
typeof config.headers === "function" ? config.headers() : (config.headers ?? {})
|
|
626
|
+
|
|
536
627
|
const baseHeaders: Record<string, string> = {
|
|
537
628
|
apikey: config.anonKey,
|
|
538
629
|
Authorization: `Bearer ${config.anonKey}`,
|
|
539
630
|
"Content-Type": "application/json",
|
|
540
|
-
...
|
|
631
|
+
...extraHeaders(),
|
|
541
632
|
}
|
|
542
633
|
|
|
543
634
|
// Create a retry-aware fetch bound to client-level config
|
|
@@ -552,10 +643,12 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
552
643
|
storageKey: config.auth?.storageKey,
|
|
553
644
|
cookiePrefix: config.auth?.cookiePrefix,
|
|
554
645
|
storage: config.auth?.storage,
|
|
646
|
+
detectSessionInUrl: config.auth?.detectSessionInUrl,
|
|
647
|
+
transport: doFetch,
|
|
555
648
|
})
|
|
556
649
|
const queryCache = config.queryCache ?? defaultQueryCache
|
|
557
650
|
|
|
558
|
-
const
|
|
651
|
+
const credentialHeaders = async (): Promise<Record<string, string>> => {
|
|
559
652
|
// Studio and other admin tools pass serviceRoleKey, use it for table/RPC/GraphQL
|
|
560
653
|
// so supatype_admin RLS policies and bypass rules apply (anon would fail).
|
|
561
654
|
if (config.serviceRoleKey) {
|
|
@@ -563,7 +656,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
563
656
|
apikey: config.serviceRoleKey,
|
|
564
657
|
Authorization: `Bearer ${config.serviceRoleKey}`,
|
|
565
658
|
"Content-Type": "application/json",
|
|
566
|
-
...
|
|
659
|
+
...extraHeaders(),
|
|
567
660
|
}
|
|
568
661
|
}
|
|
569
662
|
// A preview link is the whole credential, and it comes before any session on purpose: whoever
|
|
@@ -587,13 +680,19 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
587
680
|
return baseHeaders
|
|
588
681
|
}
|
|
589
682
|
|
|
683
|
+
// Every request's headers: its credential, then the caller's own extra headers as they are now.
|
|
684
|
+
const getAuthHeaders = async (): Promise<Record<string, string>> => ({
|
|
685
|
+
...(await credentialHeaders()),
|
|
686
|
+
...extraHeaders(),
|
|
687
|
+
})
|
|
688
|
+
|
|
590
689
|
// Storage asks for headers per request, like every other client here.
|
|
591
690
|
//
|
|
592
691
|
// It used to be handed a plain object built above, before anybody had signed in, so every storage
|
|
593
692
|
// request carried the anon key for the life of the page. An app's per-user storage policies saw
|
|
594
693
|
// `anon` rather than the caller, and through Studio's proxy the request was refused outright,
|
|
595
694
|
// because an anon key carries no `sub` and the proxy requires one.
|
|
596
|
-
const storage = new StorageClient(`${config.url}/storage/v1`, getAuthHeaders)
|
|
695
|
+
const storage = new StorageClient(`${config.url}/storage/v1`, getAuthHeaders, doFetch)
|
|
597
696
|
|
|
598
697
|
// The same provider the other sub-clients get, not `baseHeaders`.
|
|
599
698
|
//
|
|
@@ -608,6 +707,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
608
707
|
: (): Promise<void> => auth.ensureValidSession()
|
|
609
708
|
|
|
610
709
|
const functions = new FunctionsClient(config.url, getAuthHeaders, doFetch, onUnauthorized)
|
|
710
|
+
const runGraphql = createGraphqlRunner({ endpoint: `${config.url}/graphql/v1`, send: doFetch, headers: getAuthHeaders, onUnauthorized })
|
|
611
711
|
|
|
612
712
|
// Signing in has to reach an already-open socket.
|
|
613
713
|
//
|
|
@@ -626,30 +726,39 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
626
726
|
void realtime.reauthenticate()
|
|
627
727
|
})
|
|
628
728
|
|
|
729
|
+
// One place that wires a table to this client's headers, cache, auth refresh and fetch.
|
|
730
|
+
const tableClient = <
|
|
731
|
+
TDef extends TableDef,
|
|
732
|
+
TTables extends Record<string, TableDef> = Record<string, TableDef>,
|
|
733
|
+
TName extends string = string,
|
|
734
|
+
>(table: string): TableClient<TDef, TTables, TName> =>
|
|
735
|
+
new TableClient<TDef, TTables, TName>(config.url, table, getAuthHeaders, realtime, queryCache, onUnauthorized, doFetch)
|
|
736
|
+
|
|
629
737
|
return {
|
|
630
738
|
url: config.url,
|
|
631
739
|
serviceRoleKey: config.serviceRoleKey,
|
|
632
740
|
|
|
633
741
|
from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
|
|
634
742
|
table: TTable,
|
|
635
|
-
): TableClient<TDatabase["public"]["Tables"][TTable]> {
|
|
743
|
+
): TableClient<TDatabase["public"]["Tables"][TTable], TDatabase["public"]["Tables"], TTable> {
|
|
636
744
|
type TDef = TDatabase["public"]["Tables"][TTable]
|
|
637
|
-
return
|
|
745
|
+
return tableClient<TDef, TDatabase["public"]["Tables"], TTable>(table)
|
|
638
746
|
},
|
|
639
747
|
|
|
640
748
|
global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow> {
|
|
641
749
|
const tableName = `_global_${name}`
|
|
642
|
-
|
|
750
|
+
// A global is one row that always exists, so a write to it names only the fields it changes.
|
|
751
|
+
type TDef = { Row: TRow; Insert: Partial<TRow>; Update: Partial<TRow> }
|
|
643
752
|
return {
|
|
644
753
|
async get(): Promise<{ data: TRow | null; error: SupatypeError | null }> {
|
|
645
|
-
const tc =
|
|
754
|
+
const tc = tableClient<TDef, Record<string, TDef>>(tableName)
|
|
646
755
|
const result = await tc.select().limit(1).maybeSingle()
|
|
647
756
|
return { data: result.data ?? null, error: result.error }
|
|
648
757
|
},
|
|
649
758
|
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 =
|
|
759
|
+
const tc = tableClient<TDef>(tableName)
|
|
760
|
+
const result = await tc.upsert(data)
|
|
761
|
+
const row = result.data?.[0] ?? null
|
|
653
762
|
return { data: row, error: result.error }
|
|
654
763
|
},
|
|
655
764
|
}
|
|
@@ -660,50 +769,17 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
660
769
|
realtime,
|
|
661
770
|
functions,
|
|
662
771
|
|
|
663
|
-
|
|
772
|
+
/**
|
|
773
|
+
* Run a GraphQL query. Sent as a POST, so it is not retried unless `options.idempotent` says a
|
|
774
|
+
* second copy is harmless, as it is for any query that is not a mutation.
|
|
775
|
+
*/
|
|
776
|
+
async graphql<TData = unknown>(
|
|
664
777
|
query: string,
|
|
665
778
|
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 }
|
|
779
|
+
options?: { idempotent?: boolean | undefined } | undefined,
|
|
780
|
+
): Promise<{ data: TData | null; error: SupatypeError | null }> {
|
|
781
|
+
const { data, error } = await runGraphql(query, variables, options)
|
|
782
|
+
return { data: isDeclaredReturn<TData>(data) ? data : null, error }
|
|
707
783
|
},
|
|
708
784
|
|
|
709
785
|
async rpc<TFn extends FunctionNames<TDatabase>>(
|
|
@@ -711,47 +787,40 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
711
787
|
params?: FunctionArgs<TDatabase, TFn> | undefined,
|
|
712
788
|
options?: RpcOptions | undefined,
|
|
713
789
|
): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>> {
|
|
714
|
-
const headers: Record<string, string> = { ...(await getAuthHeaders()) }
|
|
715
790
|
const method = options?.head === true ? "HEAD" : "POST"
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
}
|
|
791
|
+
// Resolved per attempt, so the resend after a 401 carries the same `Prefer` and profile as
|
|
792
|
+
// the first send. It used to rebuild only `Prefer` and drop the schema.
|
|
793
|
+
const rpcHeaders = async (): Promise<Record<string, string>> => ({
|
|
794
|
+
...(await getAuthHeaders()),
|
|
795
|
+
...(options?.count !== undefined && { Prefer: `count=${options.count}` }),
|
|
796
|
+
// PostgREST resolves `/rpc/<name>` against the default profile, so a function in any other
|
|
797
|
+
// schema is unreachable without this. `Content-Profile` rather than `Accept-Profile`,
|
|
798
|
+
// because an RPC call is a POST and PostgREST reads the write-side header for it.
|
|
799
|
+
...(options?.schema !== undefined && { "Content-Profile": options.schema }),
|
|
800
|
+
})
|
|
726
801
|
|
|
727
802
|
let res: Response
|
|
728
803
|
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}`, {
|
|
804
|
+
res = await fetchWithOptional401Retry(
|
|
805
|
+
doFetch,
|
|
806
|
+
`${config.url}/rest/v1/rpc/${fn}`,
|
|
807
|
+
{
|
|
741
808
|
method,
|
|
742
|
-
headers: retryHeaders,
|
|
743
809
|
...(params !== undefined && method !== "HEAD" && { body: JSON.stringify(params) }),
|
|
744
|
-
|
|
745
|
-
|
|
810
|
+
...(options?.idempotent === true && { idempotent: true }),
|
|
811
|
+
},
|
|
812
|
+
rpcHeaders,
|
|
813
|
+
onUnauthorized,
|
|
814
|
+
)
|
|
746
815
|
} catch (e) {
|
|
747
|
-
return { data: null, error:
|
|
816
|
+
return { data: null, error: transportFailure(e) }
|
|
748
817
|
}
|
|
749
818
|
|
|
750
819
|
if (!res.ok) {
|
|
751
|
-
const body = await res
|
|
820
|
+
const body = await readJsonObject(res)
|
|
752
821
|
const pgError = PostgrestError.fromResponse(
|
|
753
822
|
{
|
|
754
|
-
message:
|
|
823
|
+
message: refusalText(body),
|
|
755
824
|
code: typeof body["code"] === "string" ? body["code"] : undefined,
|
|
756
825
|
details: typeof body["details"] === "string" ? body["details"] : undefined,
|
|
757
826
|
hint: typeof body["hint"] === "string" ? body["hint"] : undefined,
|
|
@@ -764,6 +833,8 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
764
833
|
message: pgError.message,
|
|
765
834
|
status: pgError.statusCode,
|
|
766
835
|
code: pgError.code,
|
|
836
|
+
...(pgError.hint !== null && pgError.hint !== "" && { hint: pgError.hint }),
|
|
837
|
+
...(pgError.details !== null && pgError.details !== "" && { details: pgError.details }),
|
|
767
838
|
},
|
|
768
839
|
}
|
|
769
840
|
}
|
|
@@ -772,8 +843,8 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
772
843
|
return { data: null, error: null }
|
|
773
844
|
}
|
|
774
845
|
|
|
775
|
-
const data = await res.json()
|
|
776
|
-
return { data, error: null }
|
|
846
|
+
const data = await res.json()
|
|
847
|
+
return { data: isDeclaredReturn<FunctionReturns<TDatabase, TFn>>(data) ? data : null, error: null }
|
|
777
848
|
},
|
|
778
849
|
}
|
|
779
850
|
}
|