@supatype/client 0.7.0 → 0.9.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.
Files changed (67) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +69 -56
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +28 -0
  5. package/bin/supatype-prepare.js +68 -0
  6. package/dist/auth.d.ts +17 -0
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +41 -10
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +1 -1
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/graphql-transport.d.ts +2 -2
  13. package/dist/graphql-transport.d.ts.map +1 -1
  14. package/dist/graphql-transport.js.map +1 -1
  15. package/dist/index.d.ts +16 -13
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +33 -21
  18. package/dist/index.js.map +1 -1
  19. package/dist/mutation-request.d.ts +17 -4
  20. package/dist/mutation-request.d.ts.map +1 -1
  21. package/dist/mutation-request.js +16 -14
  22. package/dist/mutation-request.js.map +1 -1
  23. package/dist/query.d.ts +40 -16
  24. package/dist/query.d.ts.map +1 -1
  25. package/dist/query.js +81 -21
  26. package/dist/query.js.map +1 -1
  27. package/dist/realtime.d.ts +38 -1
  28. package/dist/realtime.d.ts.map +1 -1
  29. package/dist/realtime.js +201 -82
  30. package/dist/realtime.js.map +1 -1
  31. package/dist/storage.d.ts.map +1 -1
  32. package/dist/storage.js +10 -3
  33. package/dist/storage.js.map +1 -1
  34. package/dist/types.d.ts +14 -0
  35. package/dist/types.d.ts.map +1 -1
  36. package/package.json +5 -2
  37. package/src/auth.ts +43 -10
  38. package/src/bindings.ts +1 -1
  39. package/src/graphql-transport.ts +2 -2
  40. package/src/index.ts +40 -26
  41. package/src/mutation-request.ts +32 -18
  42. package/src/query.ts +102 -37
  43. package/src/realtime.ts +222 -82
  44. package/src/storage.ts +11 -3
  45. package/src/types.ts +14 -0
  46. package/tests/auth.test.ts +65 -0
  47. package/tests/data-plane-auth.test.ts +1 -6
  48. package/tests/draft-insert.test.ts +9 -9
  49. package/tests/draft-update.test.ts +5 -5
  50. package/tests/helpers/socket-swap.ts +3 -0
  51. package/tests/minimal-writes.test.ts +118 -0
  52. package/tests/postgrest-error-codes.test.ts +1 -1
  53. package/tests/query.test.ts +3 -3
  54. package/tests/realtime-ack-ref.test.ts +112 -0
  55. package/tests/realtime-session-auth.test.ts +1 -4
  56. package/tests/realtime-shared-channel.test.ts +209 -0
  57. package/tests/rpc-resend.test.ts +33 -8
  58. package/tests/server-bodies.test.ts +48 -0
  59. package/tests/storage-quota-integration.test.ts +4 -7
  60. package/tests/storage-upload-limit-integration.test.ts +5 -9
  61. package/tests/storage-url-encoding.test.ts +52 -0
  62. package/tests/supatype-prepare.test.ts +139 -0
  63. package/tests/support/blob.ts +10 -0
  64. package/tests/support/jwt.ts +4 -0
  65. package/tests/table-subscribe.test.ts +28 -1
  66. package/tests/unauthorized-resend.test.ts +107 -0
  67. package/tsconfig.tsbuildinfo +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AAI1D,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAA;IACV,MAAM,EAAE,MAAM,CAAA;IACd,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACrC,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,MAAM,CAAA;IAChB,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;IACjB,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;CAClC;AAED,MAAM,WAAW,MAAM;IACrB,EAAE,EAAE,MAAM,CAAA;IACV,YAAY,CAAC,EAAE,MAAM,GAAG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;;WAMG;QACH,mBAAmB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;QACzC,oFAAoF;QACpF,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;QAC/B;;;;WAIG;QACH,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;QACjC;;;WAGG;QACH,OAAO,CAAC,EAAE,WAAW,GAAG,SAAS,CAAA;QACjC;;;;;WAKG;QACH,kBAAkB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;KACzC,GAAG,SAAS,CAAA;IACb;;;;;;;;OAQG;IACH,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAC3B;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC5B;;OAEG;IACH,UAAU,CAAC,EAAE,OAAO,kBAAkB,EAAE,UAAU,GAAG,SAAS,CAAA;IAC9D;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IACpC;;;;;;;;;;;;;;;OAeG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAChC;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,SAAS,CAAA;CAC9E"}
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "@supatype/client",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "license": "MIT",
5
5
  "description": "Supatype client SDK: typed REST, auth, storage, realtime",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
8
8
  "types": "./dist/index.d.ts",
9
+ "bin": {
10
+ "supatype-prepare": "./bin/supatype-prepare.js"
11
+ },
9
12
  "exports": {
10
13
  ".": {
11
14
  "import": "./dist/index.js",
@@ -28,7 +31,7 @@
28
31
  "build": "tsc --project tsconfig.json",
29
32
  "dev": "tsc --project tsconfig.json --watch",
30
33
  "typecheck": "tsc --project tests/tsconfig.json --noEmit",
31
- "test": "vitest run",
34
+ "test": "vitest run --maxWorkers=50%",
32
35
  "clean": "rm -rf dist *.tsbuildinfo"
33
36
  }
34
37
  }
package/src/auth.ts CHANGED
@@ -44,6 +44,10 @@ export type AuthListener = (event: AuthChangeEvent, session: Session | null) =>
44
44
  interface AuthClientOptions {
45
45
  initialSession?: Session | undefined
46
46
  persistSession?: boolean | undefined
47
+ /** Refresh on a timer before the token expires, and at once when it starts expired. Default: true. */
48
+ autoRefreshToken?: boolean | undefined
49
+ /** Refresh an expired access token when a request or `getSession` finds it. Default: true. */
50
+ refreshExpiredToken?: boolean | undefined
47
51
  storageKey?: string | undefined
48
52
  cookiePrefix?: string | undefined
49
53
  /** Custom session store (replaces browser localStorage/cookies when set). */
@@ -137,6 +141,10 @@ export class AuthClient {
137
141
  private readonly listeners = new Map<string, AuthListener>()
138
142
  private listenerIdCounter = 0
139
143
  private readonly persistSession: boolean
144
+ /** False leaves every refresh to `ensureValidSession`, which each request calls first. */
145
+ private readonly autoRefreshToken: boolean
146
+ /** False makes `ensureValidSession` leave an expired session as it is, for the server to refuse. */
147
+ private readonly refreshExpiredToken: boolean
140
148
  private readonly storageKey: string
141
149
  private readonly cookieName: string
142
150
  private readonly storage: AuthStorage | null
@@ -159,6 +167,8 @@ export class AuthClient {
159
167
  this.url = url
160
168
  this.baseHeaders = baseHeaders
161
169
  this.persistSession = opts.persistSession ?? true
170
+ this.autoRefreshToken = opts.autoRefreshToken ?? true
171
+ this.refreshExpiredToken = opts.refreshExpiredToken ?? true
162
172
  this.storageKey = opts.storageKey ?? DEFAULT_STORAGE_KEY
163
173
  const cookiePrefix = opts.cookiePrefix ?? DEFAULT_COOKIE_PREFIX
164
174
  this.cookieName = `${cookiePrefix}-auth-token`
@@ -174,7 +184,7 @@ export class AuthClient {
174
184
  // Keep the access token fresh while the app is open (and refresh immediately
175
185
  // if a persisted session loaded already expired).
176
186
  this.scheduleAutoRefresh()
177
- if (this.currentSession !== null && this.isAccessTokenExpired(this.currentSession)) {
187
+ if (this.autoRefreshToken && this.currentSession !== null && this.isAccessTokenExpired(this.currentSession)) {
178
188
  void this.ensureValidSession()
179
189
  }
180
190
  }
@@ -303,19 +313,42 @@ export class AuthClient {
303
313
  private async ensureValidSessionInternal(): Promise<void> {
304
314
  const session = this.currentSession
305
315
  if (session === null || !this.isAccessTokenExpired(session)) return
316
+ // Sent as it is: a refresh nobody can store spends a refresh token someone else holds.
317
+ if (!this.refreshExpiredToken) return
306
318
  if (!session.refreshToken?.trim()) {
307
319
  this._setSession(null)
308
320
  return
309
321
  }
310
- if (this.refreshInFlight) {
311
- await this.refreshInFlight
312
- return
322
+ await this.refreshOnce()
323
+ }
324
+
325
+ /**
326
+ * Refresh after the server refused `refusedToken` as expired or invalid, whatever the local clock
327
+ * says of it. True when the session now holds a different token, so a request refused with that
328
+ * one is worth sending again; false when signed out, when the refresh failed or handed back the
329
+ * same token, or when this client leaves expired sessions for the server to refuse.
330
+ */
331
+ async refreshRefusedSession(refusedToken: string): Promise<boolean> {
332
+ await this.ready
333
+ const session = this.currentSession
334
+ if (session === null) return false
335
+ // Another request's refresh has already replaced it.
336
+ if (session.accessToken !== refusedToken) return true
337
+ if (!this.refreshExpiredToken) return false
338
+ await this.refreshOnce()
339
+ const token = this.currentAccessToken
340
+ return token !== null && token !== refusedToken
341
+ }
342
+
343
+ /** One refresh at a time: a second caller waits for the one already in flight. */
344
+ private async refreshOnce(): Promise<void> {
345
+ if (this.refreshInFlight === null) {
346
+ this.refreshInFlight = this.refreshSession()
347
+ .then(() => undefined)
348
+ .finally(() => {
349
+ this.refreshInFlight = null
350
+ })
313
351
  }
314
- this.refreshInFlight = this.refreshSession()
315
- .then(() => undefined)
316
- .finally(() => {
317
- this.refreshInFlight = null
318
- })
319
352
  await this.refreshInFlight
320
353
  }
321
354
 
@@ -325,7 +358,7 @@ export class AuthClient {
325
358
  clearTimeout(this.refreshTimer)
326
359
  this.refreshTimer = null
327
360
  }
328
- if (typeof setTimeout === "undefined") return
361
+ if (!this.autoRefreshToken || typeof setTimeout === "undefined") return
329
362
  const session = this.currentSession
330
363
  if (session === null || !session.refreshToken) return
331
364
 
package/src/bindings.ts CHANGED
@@ -17,6 +17,6 @@ export type {
17
17
  export { startOAuthRedirect } from "./auth-redirect.js"
18
18
  export { isClientFor, isRowsOf, isCallerValue } from "./caller-types.js"
19
19
  export { runMutation } from "./mutation-request.js"
20
- export type { MutationOperation, MutationOutcome } from "./mutation-request.js"
20
+ export type { MutationOperation, MutationOutcome, MutationRequest, MutationSelect } from "./mutation-request.js"
21
21
  export { livePreviewMessage, previewMessageOf, originOf } from "./live-preview.js"
22
22
  export type { LivePreviewMessage } from "./live-preview.js"
@@ -10,7 +10,7 @@ import type { RequestTransport } from "./fetch-with-retry.js"
10
10
  import { GRAPHQL_SCHEMA_QUERY, GraphqlSchemaCache, decodeGraphqlAnswer, readGraphqlSchema, type GraphqlSchema } from "./graphql-json.js"
11
11
  import { isJsonObject, refusalText } from "./json.js"
12
12
  import { bearerRole } from "./jwt.js"
13
- import { fetchWithOptional401Retry, type HeadersProvider } from "./query.js"
13
+ import { fetchWithOptional401Retry, type HeadersProvider, type UnauthorizedHandler } from "./query.js"
14
14
  import type { SupatypeError } from "./types.js"
15
15
 
16
16
  /** Where GraphQL requests go and what they carry. Studio builds one per send-as choice. */
@@ -19,7 +19,7 @@ export type GraphqlTransport = {
19
19
  readonly endpoint: string
20
20
  readonly send: RequestTransport
21
21
  readonly headers: HeadersProvider
22
- readonly onUnauthorized?: (() => Promise<void>) | undefined
22
+ readonly onUnauthorized?: UnauthorizedHandler | undefined
23
23
  /** Whose schema a request reads, from its headers. Defaults to the bearer token's role. */
24
24
  readonly schemaKey?: ((headers: Record<string, string>) => string) | undefined
25
25
  }
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  fetchWithOptional401Retry,
8
8
  type DraftCreate,
9
9
  type HeadersProvider,
10
+ type UnauthorizedHandler,
10
11
  } from "./query.js"
11
12
  import { registeredDraftModel } from "./draft-models-registry.js"
12
13
  import { GENERATED_CLIENT_IMPORT } from "./generated-client.js"
@@ -18,7 +19,7 @@ import type { RealtimePayload } from "./realtime.js"
18
19
  import { subscribeToTable, type TableSubscribeOptions, type TableSubscription } from "./table-subscription.js"
19
20
  import { PostgrestError, transportFailure } from "./errors.js"
20
21
  import { createRetryFetch } from "./retry.js"
21
- import { isJsonObject, readJsonObject, refusalText } from "./json.js"
22
+ import { isJsonObject, isString, readJsonObject, refusalText } from "./json.js"
22
23
  import { jwtRole } from "./jwt.js"
23
24
  import { createGraphqlRunner } from "./graphql-transport.js"
24
25
  import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
@@ -91,7 +92,7 @@ export type AnyClient = SupatypeClient<AnyDatabase>
91
92
  export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
92
93
  export { AuthClient } from "./auth.js"
93
94
  export { onIdentityChange, type IdentitySource } from "./identity.js"
94
- export { QueryBuilder, MutationBuilder, type HeadersProvider, type RequestTransport } from "./query.js"
95
+ export { QueryBuilder, MutationBuilder, type HeadersProvider, type RequestTransport, type UnauthorizedHandler } from "./query.js"
95
96
  export { QueryCache, defaultQueryCache } from "./query-cache.js"
96
97
  export { StorageClient, BucketClient } from "./storage.js"
97
98
  export type { StorageObject, StorageFolder, StorageListEntry, ListOptions, RemovedObject, StorageReference, TransformOptions } from "./storage.js"
@@ -157,7 +158,7 @@ class TableClient<
157
158
  private readonly table: string
158
159
  private readonly path: string
159
160
  private readonly getHeaders: HeadersProvider
160
- private readonly onUnauthorized: (() => Promise<void>) | undefined
161
+ private readonly onUnauthorized: UnauthorizedHandler | undefined
161
162
  /** The client's retry-aware fetch, so `timeout` and `retry` reach table requests too. */
162
163
  private readonly send: RequestTransport
163
164
  private readonly queryCache: QueryCache
@@ -177,7 +178,7 @@ class TableClient<
177
178
  getHeaders: HeadersProvider,
178
179
  realtime: RealtimeClient,
179
180
  queryCache: QueryCache = defaultQueryCache,
180
- onUnauthorized: (() => Promise<void>) | undefined,
181
+ onUnauthorized: UnauthorizedHandler | undefined,
181
182
  send: RequestTransport,
182
183
  ) {
183
184
  this.baseUrl = baseUrl
@@ -251,15 +252,17 @@ class TableClient<
251
252
  }
252
253
 
253
254
  /**
254
- * Insert one row or several.
255
+ * Insert one row or several. Resolves to `data: null` unless `.select()` asks for the rows, which
256
+ * needs the right to read them as well as to write them.
255
257
  *
256
258
  * **On a model that keeps drafts**, one record is created through `supatype.create_record`, as
257
259
  * 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.
260
+ * record starts as its first draft, and with `.select()` the rows come back read from the draft
261
+ * view in the shape and order a plain insert returns. A plain insert asking for the row back is
262
+ * refused there by a read rule that hides unpublished records, because Postgres checks the
263
+ * returned row against it before anything has made the new row visible to its author. The
264
+ * generated `supatype/generated/client.ts` says which models keep drafts; a client without it
265
+ * inserts as before.
263
266
  */
264
267
  insert(
265
268
  data: TDef["Insert"] | TDef["Insert"][],
@@ -308,12 +311,13 @@ class TableClient<
308
311
  }
309
312
 
310
313
  /**
311
- * Change the rows the filters match.
314
+ * Change the rows the filters match. Resolves to `data: null` unless `.select()` asks for the rows.
312
315
  *
313
316
  * **On a model that keeps drafts** the live rows do not change: each matched record gets a new
314
317
  * 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
318
+ * none in one call, and with `.select()` the drafts come back read from the draft view. Pass
319
+ * `{ publish: true }` to publish them in the same call, so the history records the version that
320
+ * went live. The generated
317
321
  * `supatype/generated/client.ts` says which models keep drafts; elsewhere this is a plain `PATCH`, and
318
322
  * `{ publish: true }` is refused, since there is nothing to publish.
319
323
  */
@@ -391,6 +395,22 @@ function isDeclaredReturn<T>(value: unknown): value is T {
391
395
  return value !== undefined
392
396
  }
393
397
 
398
+ /**
399
+ * The message and machine-readable code on an edge function's error body. A handler may send its
400
+ * own `code`. The functions worker answers its own failures as `{ error: <code>, message }`, so
401
+ * `error` is a code when a `message` is beside it. On its own, `error` is a handler's sentence
402
+ * (`{ error: "Email already taken" }`) and is the message.
403
+ */
404
+ function functionError(body: Record<string, unknown>, status: number): SupatypeError {
405
+ const workerCode = isString(body["message"]) ? body["error"] : undefined
406
+ const code = isString(body["code"]) ? body["code"] : isString(workerCode) ? workerCode : undefined
407
+ return {
408
+ message: refusalText(body) ?? `Function returned ${status}`,
409
+ status,
410
+ ...(code !== undefined && { code }),
411
+ }
412
+ }
413
+
394
414
  /**
395
415
  * Helper type: extract function names from a database type.
396
416
  * Falls back to `string` when Functions is not defined.
@@ -473,14 +493,14 @@ export interface FunctionInvokeOptions {
473
493
  class FunctionsClient {
474
494
  private readonly baseUrl: string
475
495
  private readonly getHeaders: HeadersProvider
476
- private readonly onUnauthorized: (() => Promise<void>) | undefined
496
+ private readonly onUnauthorized: UnauthorizedHandler | undefined
477
497
  private readonly doFetch: RequestTransport
478
498
 
479
499
  constructor(
480
500
  baseUrl: string,
481
501
  getHeaders: HeadersProvider,
482
502
  doFetch: RequestTransport,
483
- onUnauthorized?: (() => Promise<void>) | undefined,
503
+ onUnauthorized?: UnauthorizedHandler | undefined,
484
504
  ) {
485
505
  this.baseUrl = baseUrl
486
506
  this.getHeaders = getHeaders
@@ -528,15 +548,7 @@ class FunctionsClient {
528
548
  )
529
549
 
530
550
  if (!res.ok) {
531
- const body = await readJsonObject(res)
532
- return {
533
- data: null,
534
- error: {
535
- message: typeof body["message"] === "string" ? body["message"] : `Function returned ${res.status}`,
536
- status: res.status,
537
- ...(typeof body["code"] === "string" ? { code: body["code"] } : {}),
538
- },
539
- }
551
+ return { data: null, error: functionError(await readJsonObject(res), res.status) }
540
552
  }
541
553
 
542
554
  const contentType = res.headers.get("content-type") ?? ""
@@ -640,6 +652,8 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
640
652
  const auth = new AuthClient(`${config.url}/auth/v1`, baseHeaders, {
641
653
  initialSession: config.initialSession,
642
654
  persistSession: config.auth?.persistSession,
655
+ autoRefreshToken: config.auth?.autoRefreshToken,
656
+ refreshExpiredToken: config.auth?.refreshExpiredToken,
643
657
  storageKey: config.auth?.storageKey,
644
658
  cookiePrefix: config.auth?.cookiePrefix,
645
659
  storage: config.auth?.storage,
@@ -704,7 +718,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
704
718
 
705
719
  const onUnauthorized = config.serviceRoleKey
706
720
  ? undefined
707
- : (): Promise<void> => auth.ensureValidSession()
721
+ : (refusedToken: string): Promise<boolean> => auth.refreshRefusedSession(refusedToken)
708
722
 
709
723
  const functions = new FunctionsClient(config.url, getAuthHeaders, doFetch, onUnauthorized)
710
724
  const runGraphql = createGraphqlRunner({ endpoint: `${config.url}/graphql/v1`, send: doFetch, headers: getAuthHeaders, onUnauthorized })
@@ -757,7 +771,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
757
771
  },
758
772
  async update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }> {
759
773
  const tc = tableClient<TDef>(tableName)
760
- const result = await tc.upsert(data)
774
+ const result = await tc.upsert(data).select<TRow>()
761
775
  const row = result.data?.[0] ?? null
762
776
  return { data: row, error: result.error }
763
777
  },
@@ -1,24 +1,38 @@
1
1
  import type { AnyClient } from "./index.js"
2
- import type { MutationBuilder } from "./query.js"
3
- import type { DraftUpdateOptions, SupatypeError } from "./types.js"
2
+ import type { DraftUpdateOptions, QueryResult, SupatypeError } from "./types.js"
4
3
  import { isRowsOf } from "./caller-types.js"
5
4
 
6
5
  export type MutationOperation = "insert" | "update" | "delete" | "upsert"
7
6
 
8
7
  export type MutationRows = Record<string, unknown> | Record<string, unknown>[]
9
8
 
9
+ /** The rows to return: `true` for every column, or the columns as `.select()` takes them. */
10
+ export type MutationSelect = true | string
11
+
12
+ /** How a binding's mutation is made beyond its operation and data. */
13
+ export interface MutationRequest extends DraftUpdateOptions {
14
+ /** Equality filters for an update or delete. */
15
+ filter?: Record<string, unknown> | undefined
16
+ /**
17
+ * Return the written rows. Without it a write returns none, as the client's own writes do:
18
+ * returning a row needs the right to read it as well as to write it.
19
+ */
20
+ select?: MutationSelect | undefined
21
+ }
22
+
10
23
  export interface MutationOutcome<TRow> {
11
24
  data: TRow[] | null
12
25
  error: SupatypeError | null
13
26
  count: number | null
14
27
  }
15
28
 
16
- type PendingMutation = MutationBuilder<Record<string, unknown>>
29
+ type PendingMutation = PromiseLike<QueryResult<unknown>>
30
+ type SelectableMutation = PendingMutation & { select(columns?: string | undefined): PendingMutation }
17
31
 
18
- function withFilter(pending: PendingMutation, filter: Record<string, unknown>): PendingMutation {
19
- let filtered = pending
20
- for (const [col, val] of Object.entries(filter)) filtered = filtered.eq(col, val)
21
- return filtered
32
+ /** The write, asking for its rows back only when `select` says to. */
33
+ function returning(write: SelectableMutation, select: MutationSelect | undefined): PendingMutation {
34
+ if (select === undefined) return write
35
+ return write.select(select === true ? undefined : select)
22
36
  }
23
37
 
24
38
  /**
@@ -33,33 +47,33 @@ function mutationRequest(
33
47
  tableClient: ReturnType<AnyClient["from"]>,
34
48
  operation: MutationOperation,
35
49
  data: MutationRows | undefined,
36
- filter: Record<string, unknown>,
37
- options: DraftUpdateOptions,
50
+ request: MutationRequest,
38
51
  ): PendingMutation | string {
39
- if (operation === "delete") return withFilter(tableClient.delete(), filter)
52
+ const filter = request.filter ?? {}
53
+ if (operation === "delete") return returning(tableClient.delete().match(filter), request.select)
40
54
  if (operation === "update") {
41
55
  if (data === undefined || Array.isArray(data)) return "update needs one object of the changes to make"
42
- return withFilter(tableClient.update(data, options), filter)
56
+ return returning(tableClient.update(data, request).match(filter), request.select)
43
57
  }
44
58
  if (data === undefined) return `${operation} needs the row or rows to write`
45
- return operation === "insert" ? tableClient.insert(data) : tableClient.upsert(data)
59
+ return returning(operation === "insert" ? tableClient.insert(data) : tableClient.upsert(data), request.select)
46
60
  }
47
61
 
48
62
  /**
49
- * Run one mutation against `table`, with the rows that come back as the caller's row type.
63
+ * Run one mutation against `table`. The outcome holds rows only when `request.select` asked for
64
+ * them, typed as the caller's row.
50
65
  *
51
- * `options` is an update's: on a model that keeps drafts, `{ publish: true }` publishes the drafts
52
- * it saves in the same call.
66
+ * `request.publish` is an update's: on a model that keeps drafts, it publishes the drafts it saves
67
+ * in the same call.
53
68
  */
54
69
  export async function runMutation<TRow>(
55
70
  client: AnyClient,
56
71
  table: string,
57
72
  operation: MutationOperation,
58
73
  data: MutationRows | undefined,
59
- filter: Record<string, unknown> = {},
60
- options: DraftUpdateOptions = {},
74
+ request: MutationRequest = {},
61
75
  ): Promise<MutationOutcome<TRow>> {
62
- const pending = mutationRequest(client.from(table), operation, data, filter, options)
76
+ const pending = mutationRequest(client.from(table), operation, data, request)
63
77
  if (typeof pending === "string") return { data: null, error: { message: pending }, count: null }
64
78
  const result = await pending
65
79
  return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error, count: result.count }