-
Notifications
You must be signed in to change notification settings - Fork 622
Expand file tree
/
Copy pathPostgrestBuilder.ts
More file actions
448 lines (423 loc) · 14.2 KB
/
PostgrestBuilder.ts
File metadata and controls
448 lines (423 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import type {
PostgrestSingleResponse,
PostgrestResponseSuccess,
CheckMatchingArrayTypes,
MergePartialResult,
IsValidResultOverride,
} from './types/types'
import { ClientServerOptions, Fetch } from './types/common/common'
import PostgrestError from './PostgrestError'
import { ContainsNull } from './select-query-parser/types'
export default abstract class PostgrestBuilder<
ClientOptions extends ClientServerOptions,
Result,
ThrowOnError extends boolean = false,
> implements
PromiseLike<
ThrowOnError extends true ? PostgrestResponseSuccess<Result> : PostgrestSingleResponse<Result>
>
{
protected method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'
protected url: URL
protected headers: Headers
protected schema?: string
protected body?: unknown
protected shouldThrowOnError = false
protected signal?: AbortSignal
protected fetch: Fetch
protected isMaybeSingle: boolean
protected urlLengthLimit: number
/**
* Creates a builder configured for a specific PostgREST request.
*
* @example
* ```ts
* import { PostgrestQueryBuilder } from '@supabase/postgrest-js'
*
* const builder = new PostgrestQueryBuilder(
* new URL('https://xyzcompany.supabase.co/rest/v1/users'),
* { headers: new Headers({ apikey: 'public-anon-key' }) }
* )
* ```
*
* @category Database
*
* @example Example 1
* ```ts
* import { PostgrestQueryBuilder } from '@supabase/postgrest-js'
*
* const builder = new PostgrestQueryBuilder(
* new URL('https://xyzcompany.supabase.co/rest/v1/users'),
* { headers: new Headers({ apikey: 'public-anon-key' }) }
* )
* ```
*/
constructor(builder: {
method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'
url: URL
headers: HeadersInit
schema?: string
body?: unknown
shouldThrowOnError?: boolean
signal?: AbortSignal
fetch?: Fetch
isMaybeSingle?: boolean
urlLengthLimit?: number
}) {
this.method = builder.method
this.url = builder.url
this.headers = new Headers(builder.headers)
this.schema = builder.schema
this.body = builder.body
this.shouldThrowOnError = builder.shouldThrowOnError ?? false
this.signal = builder.signal
this.isMaybeSingle = builder.isMaybeSingle ?? false
this.urlLengthLimit = builder.urlLengthLimit ?? 8000
if (builder.fetch) {
this.fetch = builder.fetch
} else {
this.fetch = fetch
}
}
/**
* If there's an error with the query, throwOnError will reject the promise by
* throwing the error instead of returning it as part of a successful response.
*
* {@link https://github.com/supabase/supabase-js/issues/92}
*
* @category Database
*/
throwOnError(): this & PostgrestBuilder<ClientOptions, Result, true> {
this.shouldThrowOnError = true
return this as this & PostgrestBuilder<ClientOptions, Result, true>
}
/**
* Set an HTTP header for the request.
*
* @category Database
*/
setHeader(name: string, value: string): this {
this.headers = new Headers(this.headers)
this.headers.set(name, value)
return this
}
/** *
* @category Database
*/
then<
TResult1 = ThrowOnError extends true
? PostgrestResponseSuccess<Result>
: PostgrestSingleResponse<Result>,
TResult2 = never,
>(
onfulfilled?:
| ((
value: ThrowOnError extends true
? PostgrestResponseSuccess<Result>
: PostgrestSingleResponse<Result>
) => TResult1 | PromiseLike<TResult1>)
| undefined
| null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null
): PromiseLike<TResult1 | TResult2> {
// https://postgrest.org/en/stable/api.html#switching-schemas
if (this.schema === undefined) {
// skip
} else if (['GET', 'HEAD'].includes(this.method)) {
this.headers.set('Accept-Profile', this.schema)
} else {
this.headers.set('Content-Profile', this.schema)
}
if (this.method !== 'GET' && this.method !== 'HEAD') {
this.headers.set('Content-Type', 'application/json')
}
// NOTE: Invoke w/o `this` to avoid illegal invocation error.
// https://github.com/supabase/postgrest-js/pull/247
const _fetch = this.fetch
let res = _fetch(this.url.toString(), {
method: this.method,
headers: this.headers,
body: JSON.stringify(this.body),
signal: this.signal,
}).then(async (res) => {
let error = null
let data = null
let count: number | null = null
let status = res.status
let statusText = res.statusText
if (res.ok) {
if (this.method !== 'HEAD') {
const body = await res.text()
if (body === '') {
// Prefer: return=minimal
} else if (this.headers.get('Accept') === 'text/csv') {
data = body
} else if (
this.headers.get('Accept') &&
this.headers.get('Accept')?.includes('application/vnd.pgrst.plan+text')
) {
data = body
} else {
data = JSON.parse(body)
}
}
const countHeader = this.headers.get('Prefer')?.match(/count=(exact|planned|estimated)/)
const contentRange = res.headers.get('content-range')?.split('/')
if (countHeader && contentRange && contentRange.length > 1) {
count = parseInt(contentRange[1])
}
// Fix for https://github.com/supabase/postgrest-js/issues/361 — applies to all methods.
if (this.isMaybeSingle && Array.isArray(data)) {
if (data.length > 1) {
error = {
// https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553
code: 'PGRST116',
details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`,
hint: null,
message: 'JSON object requested, multiple (or no) rows returned',
}
data = null
count = null
status = 406
statusText = 'Not Acceptable'
} else if (data.length === 1) {
data = data[0]
} else {
data = null
}
}
} else {
const body = await res.text()
try {
error = JSON.parse(body)
// Workaround for https://github.com/supabase/postgrest-js/issues/295
if (Array.isArray(error) && res.status === 404) {
data = []
error = null
status = 200
statusText = 'OK'
}
} catch {
// Workaround for https://github.com/supabase/postgrest-js/issues/295
if (res.status === 404 && body === '') {
status = 204
statusText = 'No Content'
} else {
error = {
message: body,
}
}
}
if (error && this.shouldThrowOnError) {
throw new PostgrestError(error)
}
}
const postgrestResponse = {
error,
data,
count,
status,
statusText,
}
return postgrestResponse
})
if (!this.shouldThrowOnError) {
res = res.catch((fetchError) => {
// Build detailed error information including cause if available
// Note: We don't populate code/hint for client-side network errors since those
// fields are meant for upstream service errors (PostgREST/PostgreSQL)
let errorDetails = ''
let hint = ''
let code = ''
// Add cause information if available (e.g., DNS errors, network failures)
const cause = fetchError?.cause
if (cause) {
const causeMessage = cause?.message ?? ''
const causeCode = cause?.code ?? ''
errorDetails = `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}`
errorDetails += `\n\nCaused by: ${cause?.name ?? 'Error'}: ${causeMessage}`
if (causeCode) {
errorDetails += ` (${causeCode})`
}
if (cause?.stack) {
errorDetails += `\n${cause.stack}`
}
} else {
// No cause available, just include the error stack
errorDetails = fetchError?.stack ?? ''
}
// Get URL length for potential hints
const urlLength = this.url.toString().length
// Handle AbortError specially with helpful hints
if (fetchError?.name === 'AbortError' || fetchError?.code === 'ABORT_ERR') {
code = ''
hint = 'Request was aborted (timeout or manual cancellation)'
if (urlLength > this.urlLengthLimit) {
hint += `. Note: Your request URL is ${urlLength} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`
}
}
// Handle HeadersOverflowError from undici (Node.js fetch implementation)
else if (
cause?.name === 'HeadersOverflowError' ||
cause?.code === 'UND_ERR_HEADERS_OVERFLOW'
) {
code = ''
hint = 'HTTP headers exceeded server limits (typically 16KB)'
if (urlLength > this.urlLengthLimit) {
hint += `. Your request URL is ${urlLength} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`
}
}
return {
error: {
message: `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}`,
details: errorDetails,
hint: hint,
code: code,
},
data: null,
count: null,
status: 0,
statusText: '',
}
})
}
return res.then(onfulfilled, onrejected)
}
/**
* Override the type of the returned `data`.
*
* @typeParam NewResult - The new result type to override with
* @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead
*
* @category Database
*/
returns<NewResult>(): PostgrestBuilder<
ClientOptions,
CheckMatchingArrayTypes<Result, NewResult>,
ThrowOnError
> {
/* istanbul ignore next */
return this as unknown as PostgrestBuilder<
ClientOptions,
CheckMatchingArrayTypes<Result, NewResult>,
ThrowOnError
>
}
/**
* Override the type of the returned `data` field in the response.
*
* @typeParam NewResult - The new type to cast the response data to
* @typeParam Options - Optional type configuration (defaults to { merge: true })
* @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true)
* @example
* ```typescript
* // Merge with existing types (default behavior)
* const query = supabase
* .from('users')
* .select()
* .overrideTypes<{ custom_field: string }>()
*
* // Replace existing types completely
* const replaceQuery = supabase
* .from('users')
* .select()
* .overrideTypes<{ id: number; name: string }, { merge: false }>()
* ```
* @returns A PostgrestBuilder instance with the new type
*
* @category Database
*
* @example Complete Override type of successful response
* ```ts
* const { data } = await supabase
* .from('countries')
* .select()
* .overrideTypes<Array<MyType>, { merge: false }>()
* ```
*
* @exampleResponse Complete Override type of successful response
* ```ts
* let x: typeof data // MyType[]
* ```
*
* @example Complete Override type of object response
* ```ts
* const { data } = await supabase
* .from('countries')
* .select()
* .maybeSingle()
* .overrideTypes<MyType, { merge: false }>()
* ```
*
* @exampleResponse Complete Override type of object response
* ```ts
* let x: typeof data // MyType | null
* ```
*
* @example Partial Override type of successful response
* ```ts
* const { data } = await supabase
* .from('countries')
* .select()
* .overrideTypes<Array<{ status: "A" | "B" }>>()
* ```
*
* @exampleResponse Partial Override type of successful response
* ```ts
* let x: typeof data // Array<CountryRowProperties & { status: "A" | "B" }>
* ```
*
* @example Partial Override type of object response
* ```ts
* const { data } = await supabase
* .from('countries')
* .select()
* .maybeSingle()
* .overrideTypes<{ status: "A" | "B" }>()
* ```
*
* @exampleResponse Partial Override type of object response
* ```ts
* let x: typeof data // CountryRowProperties & { status: "A" | "B" } | null
* ```
*
* @example Example 5
* ```typescript
* // Merge with existing types (default behavior)
* const query = supabase
* .from('users')
* .select()
* .overrideTypes<{ custom_field: string }>()
*
* // Replace existing types completely
* const replaceQuery = supabase
* .from('users')
* .select()
* .overrideTypes<{ id: number; name: string }, { merge: false }>()
* ```
*/
overrideTypes<
NewResult,
Options extends { merge?: boolean } = { merge: true },
>(): PostgrestBuilder<
ClientOptions,
IsValidResultOverride<Result, NewResult, false, false> extends true
? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`)
ContainsNull<Result> extends true
? MergePartialResult<NewResult, NonNullable<Result>, Options> | null
: MergePartialResult<NewResult, Result, Options>
: CheckMatchingArrayTypes<Result, NewResult>,
ThrowOnError
> {
return this as unknown as PostgrestBuilder<
ClientOptions,
IsValidResultOverride<Result, NewResult, false, false> extends true
? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`)
ContainsNull<Result> extends true
? MergePartialResult<NewResult, NonNullable<Result>, Options> | null
: MergePartialResult<NewResult, Result, Options>
: CheckMatchingArrayTypes<Result, NewResult>,
ThrowOnError
>
}
}