@supatype/client 0.1.0-alpha.10

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 (71) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/.turbo/turbo-test.log +23 -0
  3. package/.turbo/turbo-typecheck.log +4 -0
  4. package/dist/auth.d.ts +279 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +848 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/error-codes-doc.d.ts +31 -0
  9. package/dist/error-codes-doc.d.ts.map +1 -0
  10. package/dist/error-codes-doc.js +294 -0
  11. package/dist/error-codes-doc.js.map +1 -0
  12. package/dist/errors.d.ts +197 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +162 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/fetch-with-retry.d.ts +49 -0
  17. package/dist/fetch-with-retry.d.ts.map +1 -0
  18. package/dist/fetch-with-retry.js +150 -0
  19. package/dist/fetch-with-retry.js.map +1 -0
  20. package/dist/index.d.ts +151 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +285 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/query.d.ts +55 -0
  25. package/dist/query.d.ts.map +1 -0
  26. package/dist/query.js +264 -0
  27. package/dist/query.js.map +1 -0
  28. package/dist/realtime.d.ts +69 -0
  29. package/dist/realtime.d.ts.map +1 -0
  30. package/dist/realtime.js +279 -0
  31. package/dist/realtime.js.map +1 -0
  32. package/dist/retry.d.ts +24 -0
  33. package/dist/retry.d.ts.map +1 -0
  34. package/dist/retry.js +25 -0
  35. package/dist/retry.js.map +1 -0
  36. package/dist/serverless-docs.d.ts +38 -0
  37. package/dist/serverless-docs.d.ts.map +1 -0
  38. package/dist/serverless-docs.js +83 -0
  39. package/dist/serverless-docs.js.map +1 -0
  40. package/dist/storage.d.ts +102 -0
  41. package/dist/storage.d.ts.map +1 -0
  42. package/dist/storage.js +169 -0
  43. package/dist/storage.js.map +1 -0
  44. package/dist/types.d.ts +212 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/types.js +3 -0
  47. package/dist/types.js.map +1 -0
  48. package/package.json +26 -0
  49. package/src/auth.ts +1024 -0
  50. package/src/error-codes-doc.ts +315 -0
  51. package/src/errors.ts +201 -0
  52. package/src/fetch-with-retry.ts +200 -0
  53. package/src/index.ts +518 -0
  54. package/src/query.ts +331 -0
  55. package/src/realtime.ts +418 -0
  56. package/src/retry.ts +35 -0
  57. package/src/serverless-docs.ts +107 -0
  58. package/src/storage.ts +234 -0
  59. package/src/types.ts +264 -0
  60. package/tests/auth.test.ts +351 -0
  61. package/tests/mfa-totp-integration.test.ts +359 -0
  62. package/tests/query.test.ts +286 -0
  63. package/tests/rate-limit-integration.test.ts +185 -0
  64. package/tests/realtime-multi-tenant-integration.test.ts +372 -0
  65. package/tests/retry-integration.test.ts +212 -0
  66. package/tests/serverless.test.ts +115 -0
  67. package/tests/storage-quota-integration.test.ts +189 -0
  68. package/tests/storage-upload-limit-integration.test.ts +185 -0
  69. package/tests/types.test.ts +137 -0
  70. package/tsconfig.json +11 -0
  71. package/tsconfig.tsbuildinfo +1 -0
package/src/index.ts ADDED
@@ -0,0 +1,518 @@
1
+ import { AuthClient } from "./auth.js"
2
+ import { QueryBuilder, MutationBuilder } from "./query.js"
3
+ import { StorageClient } from "./storage.js"
4
+ import { RealtimeClient } from "./realtime.js"
5
+ import { PostgrestError } from "./errors.js"
6
+ import { createRetryFetch } from "./retry.js"
7
+ import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
8
+ import type {
9
+ AnyDatabase,
10
+ AugmentedDatabase,
11
+ FunctionDef,
12
+ RpcResult,
13
+ SupatypeFunctions,
14
+ SupatypeClientConfig,
15
+ SupatypeError,
16
+ } from "./types.js"
17
+
18
+ export type {
19
+ User,
20
+ Session,
21
+ AuthChangeEvent,
22
+ SupatypeError,
23
+ QueryResult,
24
+ RpcResult,
25
+ AnyDatabase,
26
+ SupatypeClientConfig,
27
+ FunctionDef,
28
+ TableDef,
29
+ TableInsert,
30
+ SupatypeModels,
31
+ SupatypeBuckets,
32
+ SupatypeFunctions,
33
+ AugmentedDatabase,
34
+ } from "./types.js"
35
+ export { AuthClient } from "./auth.js"
36
+ export { QueryBuilder, MutationBuilder } from "./query.js"
37
+ export { StorageClient, BucketClient } from "./storage.js"
38
+ export type { StorageObject, TransformOptions } from "./storage.js"
39
+ export { RealtimeClient } from "./realtime.js"
40
+ export type { RealtimeEvent, RealtimePayload, ChannelStatus, PresenceEntry } from "./realtime.js"
41
+ export * from "./errors.js"
42
+ export { fetchWithRetry, detectServerlessEnvironment, warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
43
+ export type { FetchOptions, ServerlessDetectionResult } from "./fetch-with-retry.js"
44
+ export { createRetryFetch } from "./retry.js"
45
+ export type { RetryConfig } from "./retry.js"
46
+ export { ERROR_CODES_DOCUMENTATION, getErrorDocumentation, getErrorCodesByCategory } from "./error-codes-doc.js"
47
+ export type { ErrorCodeEntry } from "./error-codes-doc.js"
48
+ export { CONNECTION_MODES, SERVERLESS_CONNECTION_WARNING, CONNECTION_FAQ } from "./serverless-docs.js"
49
+ export type { ConnectionModeDoc } from "./serverless-docs.js"
50
+
51
+ // ─── Table client ─────────────────────────────────────────────────────────────
52
+
53
+ interface TableDef {
54
+ Row: Record<string, unknown>
55
+ Insert: Record<string, unknown>
56
+ Update: Record<string, unknown>
57
+ }
58
+
59
+ class TableClient<TDef extends TableDef> {
60
+ private readonly baseUrl: string
61
+ private readonly path: string
62
+ private readonly headers: Record<string, string>
63
+
64
+ constructor(baseUrl: string, table: string, headers: Record<string, string>) {
65
+ this.baseUrl = baseUrl
66
+ this.path = `/rest/v1/${table}`
67
+ this.headers = headers
68
+ }
69
+
70
+ /**
71
+ * Start a SELECT query.
72
+ *
73
+ * Pass a type parameter to narrow the result when embedding relations:
74
+ * ```ts
75
+ * client.from('posts').select<Post & { comments: Comment[] }>('*, comments(*)')
76
+ * ```
77
+ * Without a type parameter the full Row type is returned.
78
+ */
79
+ select<TResult = TDef["Row"]>(columns?: string | undefined): QueryBuilder<TResult> {
80
+ return new QueryBuilder<TResult>(this.baseUrl, this.path, this.headers, columns)
81
+ }
82
+
83
+ insert(
84
+ data: TDef["Insert"] | TDef["Insert"][],
85
+ ): MutationBuilder<TDef["Row"]> {
86
+ return new MutationBuilder<TDef["Row"]>(
87
+ this.baseUrl,
88
+ this.path,
89
+ this.headers,
90
+ "POST",
91
+ data,
92
+ )
93
+ }
94
+
95
+ upsert(
96
+ data: TDef["Insert"] | TDef["Insert"][],
97
+ ): MutationBuilder<TDef["Row"]> {
98
+ return new MutationBuilder<TDef["Row"]>(
99
+ this.baseUrl,
100
+ this.path,
101
+ this.headers,
102
+ "POST",
103
+ data,
104
+ { upsert: true },
105
+ )
106
+ }
107
+
108
+ update(data: TDef["Update"]): MutationBuilder<TDef["Row"]> {
109
+ return new MutationBuilder<TDef["Row"]>(
110
+ this.baseUrl,
111
+ this.path,
112
+ this.headers,
113
+ "PATCH",
114
+ data,
115
+ )
116
+ }
117
+
118
+ delete(): MutationBuilder<TDef["Row"]> {
119
+ return new MutationBuilder<TDef["Row"]>(
120
+ this.baseUrl,
121
+ this.path,
122
+ this.headers,
123
+ "DELETE",
124
+ )
125
+ }
126
+ }
127
+
128
+ // ─── Main client ──────────────────────────────────────────────────────────────
129
+
130
+ export interface GlobalClient<TRow extends Record<string, unknown> = Record<string, unknown>> {
131
+ get(): Promise<{ data: TRow | null; error: SupatypeError | null }>
132
+ update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }>
133
+ }
134
+
135
+ function jwtRole(token: string): string | null {
136
+ const parts = token.split(".")
137
+ if (parts.length !== 3) return null
138
+ try {
139
+ const payloadJson =
140
+ typeof atob === "function"
141
+ ? atob(parts[1] ?? "")
142
+ : Buffer.from(parts[1] ?? "", "base64").toString("utf-8")
143
+ const payload = JSON.parse(payloadJson) as Record<string, unknown>
144
+ return typeof payload["role"] === "string" ? payload["role"] : null
145
+ } catch {
146
+ return null
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Helper type: extract function names from a database type.
152
+ * Falls back to `string` when Functions is not defined.
153
+ */
154
+ type FunctionNames<TDatabase extends AnyDatabase> =
155
+ TDatabase["public"] extends { Functions: infer F }
156
+ ? F extends Record<string, FunctionDef>
157
+ ? keyof F & string
158
+ : string
159
+ : string
160
+
161
+ /**
162
+ * Helper type: extract the Args type for a named function.
163
+ * Falls back to `Record<string, unknown>` when not typed.
164
+ */
165
+ type FunctionArgs<TDatabase extends AnyDatabase, TFn extends string> =
166
+ TDatabase["public"] extends { Functions: infer F }
167
+ ? F extends Record<string, FunctionDef>
168
+ ? TFn extends keyof F
169
+ ? F[TFn]["Args"]
170
+ : Record<string, unknown>
171
+ : Record<string, unknown>
172
+ : Record<string, unknown>
173
+
174
+ /**
175
+ * Helper type: extract the Returns type for a named function.
176
+ * Falls back to `unknown` when not typed.
177
+ */
178
+ type FunctionReturns<TDatabase extends AnyDatabase, TFn extends string> =
179
+ TDatabase["public"] extends { Functions: infer F }
180
+ ? F extends Record<string, FunctionDef>
181
+ ? TFn extends keyof F
182
+ ? F[TFn]["Returns"]
183
+ : unknown
184
+ : unknown
185
+ : unknown
186
+
187
+ type EdgeFunctionNames =
188
+ [keyof SupatypeFunctions] extends [never]
189
+ ? string
190
+ : keyof SupatypeFunctions & string
191
+
192
+ type EdgeFunctionArgs<TFn extends string> =
193
+ [keyof SupatypeFunctions] extends [never]
194
+ ? unknown
195
+ : TFn extends keyof SupatypeFunctions
196
+ ? SupatypeFunctions[TFn] extends FunctionDef
197
+ ? SupatypeFunctions[TFn]["Args"]
198
+ : unknown
199
+ : unknown
200
+
201
+ type EdgeFunctionReturns<TFn extends string> =
202
+ [keyof SupatypeFunctions] extends [never]
203
+ ? unknown
204
+ : TFn extends keyof SupatypeFunctions
205
+ ? SupatypeFunctions[TFn] extends FunctionDef
206
+ ? SupatypeFunctions[TFn]["Returns"]
207
+ : unknown
208
+ : unknown
209
+
210
+ // ─── Functions client ─────────────────────────────────────────────────────────
211
+
212
+ export interface FunctionInvokeOptions {
213
+ /** HTTP method. Default: POST */
214
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | undefined
215
+ /** Request headers (merged with defaults) */
216
+ headers?: Record<string, string> | undefined
217
+ /** Request body (JSON-serialisable) */
218
+ body?: unknown | undefined
219
+ }
220
+
221
+ class FunctionsClient {
222
+ private readonly baseUrl: string
223
+ private readonly headers: Record<string, string>
224
+ private readonly doFetch: (url: string, init?: RequestInit) => Promise<Response>
225
+
226
+ constructor(baseUrl: string, headers: Record<string, string>, doFetch: (url: string, init?: RequestInit) => Promise<Response>) {
227
+ this.baseUrl = baseUrl
228
+ this.headers = headers
229
+ this.doFetch = doFetch
230
+ }
231
+
232
+ /**
233
+ * Invoke an edge function by name.
234
+ *
235
+ * ```ts
236
+ * const { data, error } = await supatype.functions.invoke('process-order', {
237
+ * body: { items: [...], address: {...} },
238
+ * })
239
+ * ```
240
+ *
241
+ * The current user's JWT is automatically included in the Authorization header.
242
+ */
243
+ async invoke<TFn extends EdgeFunctionNames>(
244
+ functionName: TFn,
245
+ options?: (Omit<FunctionInvokeOptions, "body"> & { body?: EdgeFunctionArgs<TFn> | undefined }) | undefined,
246
+ ): Promise<{ data: EdgeFunctionReturns<TFn> | null; error: SupatypeError | null }> {
247
+ const method = options?.method ?? "POST"
248
+ const mergedHeaders: Record<string, string> = {
249
+ ...this.headers,
250
+ ...options?.headers,
251
+ }
252
+
253
+ const fetchOpts: RequestInit = {
254
+ method,
255
+ headers: mergedHeaders,
256
+ }
257
+
258
+ if (options?.body !== undefined && method !== "GET") {
259
+ fetchOpts.body = JSON.stringify(options.body)
260
+ }
261
+
262
+ try {
263
+ const res = await this.doFetch(
264
+ `${this.baseUrl}/functions/v1/${functionName}`,
265
+ fetchOpts,
266
+ )
267
+
268
+ if (!res.ok) {
269
+ const body = await res.json().catch(() => ({})) as Record<string, unknown>
270
+ return {
271
+ data: null,
272
+ error: {
273
+ message: typeof body["message"] === "string" ? body["message"] : `Function returned ${res.status}`,
274
+ status: res.status,
275
+ ...(typeof body["code"] === "string" ? { code: body["code"] } : {}),
276
+ },
277
+ }
278
+ }
279
+
280
+ const contentType = res.headers.get("content-type") ?? ""
281
+ if (contentType.includes("application/json")) {
282
+ const data = await res.json() as EdgeFunctionReturns<TFn>
283
+ return { data, error: null }
284
+ }
285
+
286
+ // Return text for non-JSON responses
287
+ const text = await res.text()
288
+ return { data: text as unknown as EdgeFunctionReturns<TFn>, error: null }
289
+ } catch (e) {
290
+ return {
291
+ data: null,
292
+ error: { message: e instanceof Error ? e.message : "Network error" },
293
+ }
294
+ }
295
+ }
296
+ }
297
+
298
+ export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabase> {
299
+ url: string
300
+ /** Service role key, if provided at construction time. Used by developer tools for admin API calls. */
301
+ serviceRoleKey: string | undefined
302
+ from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
303
+ table: TTable,
304
+ ): TableClient<TDatabase["public"]["Tables"][TTable]>
305
+ global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow>
306
+ auth: AuthClient
307
+ storage: StorageClient
308
+ realtime: RealtimeClient
309
+ functions: FunctionsClient
310
+ graphql(
311
+ query: string,
312
+ variables?: Record<string, unknown> | undefined,
313
+ ): Promise<{ data: unknown; error: SupatypeError | null }>
314
+ /**
315
+ * Call a Postgres function via PostgREST's `/rpc/function_name` endpoint.
316
+ *
317
+ * ```ts
318
+ * const { data, error } = await supatype.rpc('calculate_shipping', {
319
+ * weight: 2.5,
320
+ * country: 'GB',
321
+ * })
322
+ * ```
323
+ *
324
+ * When the database type includes `Functions`, parameters and return type
325
+ * are fully typed.
326
+ */
327
+ rpc<TFn extends FunctionNames<TDatabase>>(
328
+ fn: TFn,
329
+ params?: FunctionArgs<TDatabase, TFn> | undefined,
330
+ options?: { head?: boolean | undefined; count?: "exact" | "planned" | "estimated" | undefined } | undefined,
331
+ ): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>>
332
+ }
333
+
334
+ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
335
+ config: SupatypeClientConfig,
336
+ ): SupatypeClient<TDatabase> {
337
+ // Warn early if a direct Postgres URL is used in a serverless environment
338
+ warnIfServerlessDirectConnection(config.url)
339
+
340
+ const baseHeaders: Record<string, string> = {
341
+ apikey: config.anonKey,
342
+ Authorization: `Bearer ${config.anonKey}`,
343
+ "Content-Type": "application/json",
344
+ }
345
+
346
+ // Create a retry-aware fetch bound to client-level config
347
+ const doFetch = createRetryFetch({
348
+ retry: config.retry,
349
+ timeout: config.timeout,
350
+ })
351
+
352
+ const auth = new AuthClient(`${config.url}/auth/v1`, baseHeaders, {
353
+ initialSession: config.initialSession,
354
+ persistSession: config.auth?.persistSession,
355
+ storageKey: config.auth?.storageKey,
356
+ cookiePrefix: config.auth?.cookiePrefix,
357
+ })
358
+ // Storage admin operations (listBuckets, createBucket, etc.) require service_role.
359
+ // When a service role key is provided (developer tools like Studio), use it for
360
+ // storage so admin calls are authorised; otherwise fall back to the anon headers.
361
+ const storageHeaders: Record<string, string> = config.serviceRoleKey
362
+ ? {
363
+ apikey: config.serviceRoleKey,
364
+ Authorization: `Bearer ${config.serviceRoleKey}`,
365
+ "Content-Type": "application/json",
366
+ }
367
+ : baseHeaders
368
+ const storage = new StorageClient(`${config.url}/storage/v1`, storageHeaders)
369
+ const realtime = new RealtimeClient(`${config.url}/realtime/v1`, baseHeaders)
370
+ const functions = new FunctionsClient(config.url, baseHeaders, doFetch)
371
+
372
+ const getAuthHeaders = (): Record<string, string> => {
373
+ // Studio and other admin tools pass serviceRoleKey — use it for table/RPC/GraphQL
374
+ // so supatype_admin RLS policies and bypass rules apply (anon would fail).
375
+ if (config.serviceRoleKey) {
376
+ return {
377
+ apikey: config.serviceRoleKey,
378
+ Authorization: `Bearer ${config.serviceRoleKey}`,
379
+ "Content-Type": "application/json",
380
+ }
381
+ }
382
+ const token = auth.currentAccessToken
383
+ if (token !== null) {
384
+ const role = jwtRole(token)
385
+ // Guardrail: malformed sessions can carry a JWT with empty role, which
386
+ // PostgREST rejects ("role \"\" does not exist"). Fall back to anon.
387
+ if (role !== null && role.trim().length > 0) {
388
+ return { ...baseHeaders, Authorization: `Bearer ${token}` }
389
+ }
390
+ }
391
+ return baseHeaders
392
+ }
393
+
394
+ return {
395
+ url: config.url,
396
+ serviceRoleKey: config.serviceRoleKey,
397
+
398
+ from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
399
+ table: TTable,
400
+ ): TableClient<TDatabase["public"]["Tables"][TTable]> {
401
+ type TDef = TDatabase["public"]["Tables"][TTable]
402
+ return new TableClient<TDef>(config.url, table, getAuthHeaders())
403
+ },
404
+
405
+ global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow> {
406
+ const tableName = `_global_${name}`
407
+ type TDef = { Row: TRow; Insert: TRow; Update: Partial<TRow> }
408
+ return {
409
+ async get(): Promise<{ data: TRow | null; error: SupatypeError | null }> {
410
+ const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders())
411
+ const result = await tc.select().limit(1).maybeSingle()
412
+ return { data: result.data ?? null, error: result.error }
413
+ },
414
+ async update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }> {
415
+ const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders())
416
+ const result = await tc.upsert(data as TRow)
417
+ const row = Array.isArray(result.data) ? (result.data[0] as TRow | undefined) ?? null : null
418
+ return { data: row, error: result.error }
419
+ },
420
+ }
421
+ },
422
+
423
+ auth,
424
+ storage,
425
+ realtime,
426
+ functions,
427
+
428
+ async graphql(
429
+ query: string,
430
+ variables?: Record<string, unknown> | undefined,
431
+ ): Promise<{ data: unknown; error: SupatypeError | null }> {
432
+ const body: Record<string, unknown> = { query }
433
+ if (variables !== undefined) {
434
+ body["variables"] = variables
435
+ }
436
+ let res: Response
437
+ try {
438
+ res = await doFetch(`${config.url}/graphql/v1`, {
439
+ method: "POST",
440
+ headers: getAuthHeaders(),
441
+ body: JSON.stringify(body),
442
+ })
443
+ } catch (e) {
444
+ return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
445
+ }
446
+ let json: Record<string, unknown>
447
+ try {
448
+ json = await res.json() as Record<string, unknown>
449
+ } catch {
450
+ return { data: null, error: { message: `GraphQL endpoint returned a non-JSON response (HTTP ${res.status} ${res.statusText})` } }
451
+ }
452
+ if (!res.ok) {
453
+ const message =
454
+ typeof json["message"] === "string" ? json["message"]
455
+ : typeof json["error"] === "string" ? json["error"]
456
+ : `GraphQL request failed (HTTP ${res.status})`
457
+ return { data: json["data"] ?? null, error: { message, status: res.status } }
458
+ }
459
+ if (json["errors"] !== undefined) {
460
+ const errors = json["errors"] as Array<{ message: string }>
461
+ return { data: json["data"] ?? null, error: { message: (errors[0]?.message ?? "GraphQL error") } }
462
+ }
463
+ return { data: json["data"] ?? null, error: null }
464
+ },
465
+
466
+ async rpc<TFn extends FunctionNames<TDatabase>>(
467
+ fn: TFn,
468
+ params?: FunctionArgs<TDatabase, TFn> | undefined,
469
+ options?: { head?: boolean | undefined; count?: "exact" | "planned" | "estimated" | undefined } | undefined,
470
+ ): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>> {
471
+ const headers: Record<string, string> = { ...getAuthHeaders() }
472
+ const method = options?.head === true ? "HEAD" : "POST"
473
+
474
+ if (options?.count !== undefined) {
475
+ headers["Prefer"] = `count=${options.count}`
476
+ }
477
+
478
+ let res: Response
479
+ try {
480
+ res = await doFetch(`${config.url}/rest/v1/rpc/${fn}`, {
481
+ method,
482
+ headers,
483
+ ...(params !== undefined && method !== "HEAD" && { body: JSON.stringify(params) }),
484
+ })
485
+ } catch (e) {
486
+ return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
487
+ }
488
+
489
+ if (!res.ok) {
490
+ const body = await res.json().catch(() => ({})) as Record<string, unknown>
491
+ const pgError = PostgrestError.fromResponse(
492
+ {
493
+ message: typeof body["message"] === "string" ? body["message"] : undefined,
494
+ code: typeof body["code"] === "string" ? body["code"] : undefined,
495
+ details: typeof body["details"] === "string" ? body["details"] : undefined,
496
+ hint: typeof body["hint"] === "string" ? body["hint"] : undefined,
497
+ },
498
+ res.status,
499
+ )
500
+ return {
501
+ data: null,
502
+ error: {
503
+ message: pgError.message,
504
+ status: pgError.statusCode,
505
+ code: pgError.code,
506
+ },
507
+ }
508
+ }
509
+
510
+ if (method === "HEAD" || res.status === 204) {
511
+ return { data: null, error: null }
512
+ }
513
+
514
+ const data = await res.json() as FunctionReturns<TDatabase, TFn>
515
+ return { data, error: null }
516
+ },
517
+ }
518
+ }