Skip to content
This repository was archived by the owner on Oct 9, 2025. It is now read-only.
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
19 changes: 15 additions & 4 deletions src/PostgrestClient.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import PostgrestQueryBuilder from './lib/PostgrestQueryBuilder'
import PostgrestRpcBuilder from './lib/PostgrestRpcBuilder'
import PostgrestTransformBuilder from './lib/PostgrestTransformBuilder'

export default class PostgrestClient {
Expand Down Expand Up @@ -47,11 +48,21 @@ export default class PostgrestClient {
*
* @param fn The function name to call.
* @param params The parameters to pass to the function call.
* @param count Count algorithm to use to count rows in a table.
*/
rpc<T = any>(fn: string, params?: object): PostgrestTransformBuilder<T> {
rpc<T = any>(
fn: string,
params?: object,
{
count = null,
}: {
count?: null | 'exact' | 'planned' | 'estimated'
} = {}
): PostgrestTransformBuilder<T> {
const url = `${this.url}/rpc/${fn}`
return new PostgrestQueryBuilder<T>(url, { headers: this.headers, schema: this.schema }).rpc(
params
)
return new PostgrestRpcBuilder<T>(url, {
headers: this.headers,
schema: this.schema,
}).rpc(params, { count })
}
}
23 changes: 0 additions & 23 deletions src/lib/PostgrestQueryBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { PostgrestBuilder } from './types'
import PostgrestFilterBuilder from './PostgrestFilterBuilder'
import PostgrestTransformBuilder from './PostgrestTransformBuilder'

export default class PostgrestQueryBuilder<T> extends PostgrestBuilder<T> {
constructor(
Expand Down Expand Up @@ -142,26 +141,4 @@ export default class PostgrestQueryBuilder<T> extends PostgrestBuilder<T> {
this.headers['Prefer'] = prefersHeaders.join(',')
return new PostgrestFilterBuilder(this)
}

/** @internal */
rpc(
params?: object,
{
head = false,
count = null,
}: {
head?: boolean
count?: null | 'exact' | 'planned' | 'estimated'
} = {}
): PostgrestTransformBuilder<T> {
this.method = 'POST'
this.body = params
if (count) {
this.headers['Prefer'] = `count=${count}`
}
if (head) {
this.method = 'HEAD'
}
return new PostgrestTransformBuilder(this)
}
}
36 changes: 36 additions & 0 deletions src/lib/PostgrestRpcBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { PostgrestBuilder } from './types'
import PostgrestTransformBuilder from './PostgrestTransformBuilder'

export default class PostgrestRpcBuilder<T> extends PostgrestBuilder<T> {
constructor(
url: string,
{ headers = {}, schema }: { headers?: { [key: string]: string }; schema?: string } = {}
) {
super({} as PostgrestBuilder<T>)
this.url = new URL(url)
this.headers = { ...headers }
this.schema = schema
}

/**
* Perform a stored procedure call.
*/
rpc(
params?: object,
{
count = null,
}: {
count?: null | 'exact' | 'planned' | 'estimated'
} = {}
): PostgrestTransformBuilder<T> {
this.method = 'POST'
this.body = params

if (count) {
if (this.headers['Prefer'] !== undefined) this.headers['Prefer'] += `,count=${count}`
else this.headers['Prefer'] = `count=${count}`
}

return new PostgrestTransformBuilder(this)
}
}
30 changes: 12 additions & 18 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,32 +83,26 @@ export abstract class PostgrestBuilder<T> implements PromiseLike<PostgrestRespon
body: JSON.stringify(this.body),
})
.then(async (res) => {
let error, data, count
let error = null
let data = null
let count = null

if (res.ok) {
error = null
if (this.method !== 'HEAD') {
const isReturnMinimal = this.headers['Prefer']?.split(',').includes('return=minimal')
data = isReturnMinimal ? null : await res.json()
} else {
data = null
const isReturnMinimal = this.headers['Prefer']?.split(',').includes('return=minimal')
if (this.method !== 'HEAD' && !isReturnMinimal) {
const text = await res.text()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will res.text ever be undefined here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (text && text !== '') data = JSON.parse(text)
}

const countHeader = this.headers['Prefer']?.match(/count=(exact|planned|estimated)/)
if (countHeader) {
const contentRange = res.headers.get('content-range')?.split('/')
if (contentRange && contentRange.length > 1) {
count = parseInt(contentRange[1])
} else {
count = null
}
} else {
count = null
const contentRange = res.headers.get('content-range')?.split('/')
if (countHeader && contentRange && contentRange.length > 1) {
count = parseInt(contentRange[1])
}
} else {
error = await res.json()
data = null
count = null
}

const postgrestResponse: PostgrestResponse<T> = {
error,
data,
Expand Down
32 changes: 11 additions & 21 deletions test/__snapshots__/index.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -2883,35 +2883,25 @@ Object {
}
`;

exports[`stored procedure with count: 'exact' 1`] = `
exports[`stored procedure returns void 1`] = `
Object {
"body": null,
"count": null,
"data": null,
"error": Object {
"code": "42883",
"details": null,
"hint": "No function matches the given name and argument types. You might need to add explicit type casts.",
"message": "function public.get_status(count => text, name_param => text) does not exist",
},
"status": 404,
"statusText": "Not Found",
"error": null,
"status": 200,
"statusText": "OK",
}
`;

exports[`stored procedure with count: 'exact', head: true 1`] = `
exports[`stored procedure with count: 'exact' 1`] = `
Object {
"body": null,
"count": null,
"data": null,
"error": Object {
"code": "42883",
"details": null,
"hint": "No function matches the given name and argument types. You might need to add explicit type casts.",
"message": "function public.get_status(count => text, head => text, name_param => text) does not exist",
},
"status": 404,
"statusText": "Not Found",
"body": "ONLINE",
"count": 1,
"data": "ONLINE",
"error": null,
"status": 200,
"statusText": "OK",
}
`;

Expand Down
16 changes: 6 additions & 10 deletions test/basic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ test('stored procedure', async () => {
expect(res).toMatchSnapshot()
})

test('stored procedure returns void', async () => {
const res = await postgrest.rpc('void_func')
expect(res).toMatchSnapshot()
})

test('custom headers', async () => {
const postgrest = new PostgrestClient(REST_URL, { headers: { apikey: 'foo' } })
expect((postgrest.from('users').select() as any).headers['apikey']).toEqual('foo')
Expand Down Expand Up @@ -171,16 +176,7 @@ test('select with count:exact', async () => {
})

test("stored procedure with count: 'exact'", async () => {
const res = await postgrest.rpc('get_status', { name_param: 'supabot', count: 'exact' })
expect(res).toMatchSnapshot()
})

test("stored procedure with count: 'exact', head: true", async () => {
const res = await postgrest.rpc('get_status', {
name_param: 'supabot',
count: 'exact',
head: true,
})
const res = await postgrest.rpc('get_status', { name_param: 'supabot'}, {count: 'exact' })
expect(res).toMatchSnapshot()
})

Expand Down
4 changes: 4 additions & 0 deletions test/db/00-schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ RETURNS TABLE(username text, status user_status) AS $$
SELECT username, status from users WHERE username=name_param;
$$ LANGUAGE SQL IMMUTABLE;

CREATE FUNCTION public.void_func()
RETURNS void AS $$
$$ LANGUAGE SQL;

-- SECOND SCHEMA USERS
CREATE TYPE personal.user_status AS ENUM ('ONLINE', 'OFFLINE');
CREATE TABLE personal.users(
Expand Down