Skip to content

Implement unwrap() to throw query errors instead of returning them #188

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,23 @@ export abstract class PostgrestBuilder<T> implements PromiseLike<PostgrestRespon
protected headers!: { [key: string]: string }
protected schema?: string
protected body?: Partial<T> | Partial<T>[]
protected shouldThrowOnError?: boolean

constructor(builder: PostgrestBuilder<T>) {
Object.assign(this, builder)
}

/**
* 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}
*/
throwOnError(): PostgrestBuilder<T> {
this.shouldThrowOnError = true
return this
}

then<TResult1 = PostgrestResponse<T>, TResult2 = never>(
onfulfilled?:
| ((value: PostgrestResponse<T>) => TResult1 | PromiseLike<TResult1>)
Expand Down Expand Up @@ -91,7 +103,8 @@ export abstract class PostgrestBuilder<T> implements PromiseLike<PostgrestRespon
const isReturnMinimal = this.headers['Prefer']?.split(',').includes('return=minimal')
if (this.method !== 'HEAD' && !isReturnMinimal) {
const text = await res.text()
if (text && text !== '' && this.headers['Accept'] !== 'text/csv') data = JSON.parse(text)
if (text && text !== '' && this.headers['Accept'] !== 'text/csv')
data = JSON.parse(text)
}

const countHeader = this.headers['Prefer']?.match(/count=(exact|planned|estimated)/)
Expand All @@ -101,6 +114,10 @@ export abstract class PostgrestBuilder<T> implements PromiseLike<PostgrestRespon
}
} else {
error = await res.json()

if (error && this.shouldThrowOnError) {
throw error
}
}

const postgrestResponse: PostgrestResponse<T> = {
Expand All @@ -111,6 +128,7 @@ export abstract class PostgrestBuilder<T> implements PromiseLike<PostgrestRespon
statusText: res.statusText,
body: data,
}

return postgrestResponse
})
.then(onfulfilled, onrejected)
Expand Down
11 changes: 11 additions & 0 deletions test/__snapshots__/index.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,8 @@ Object {
}
`;

exports[`connection errors should work the same with throwOnError 1`] = `[FetchError: request to http://this.url.does.not.exist/user?select=* failed, reason: getaddrinfo ENOTFOUND this.url.does.not.exist]`;

exports[`don't mutate PostgrestClient.headers 1`] = `null`;

exports[`embedded filters embedded eq 1`] = `
Expand Down Expand Up @@ -2251,3 +2253,12 @@ Object {
"statusText": "OK",
}
`;

exports[`throwOnError throws errors instead of returning them 1`] = `
Object {
"code": "42P01",
"details": null,
"hint": null,
"message": "relation \\"public.missing_table\\" does not exist",
}
`;
27 changes: 27 additions & 0 deletions test/basic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,19 @@ test('missing table', async () => {
expect(res).toMatchSnapshot()
})

test('throwOnError throws errors instead of returning them', async () => {
let isErrorCaught = false

try {
await postgrest.from('missing_table').select().throwOnError()
} catch (error) {
expect(error).toMatchSnapshot()
isErrorCaught = true
}

expect(isErrorCaught).toBe(true)
})

test('connection error', async () => {
const postgrest = new PostgrestClient('http://this.url.does.not.exist')
let isErrorCaught = false
Expand All @@ -107,6 +120,20 @@ test('connection error', async () => {
expect(isErrorCaught).toBe(true)
})

test('connection errors should work the same with throwOnError', async () => {
const postgrest = new PostgrestClient('http://this.url.does.not.exist')
let isErrorCaught = false
await postgrest
.from('user')
.select()
.throwOnError()
.then(undefined, (error) => {
expect(error).toMatchSnapshot()
isErrorCaught = true
})
expect(isErrorCaught).toBe(true)
})

test('custom type', async () => {
interface User {
username: string
Expand Down