-
-
Notifications
You must be signed in to change notification settings - Fork 130
/
PostgrestClient.ts
68 lines (63 loc) · 1.75 KB
/
PostgrestClient.ts
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
import PostgrestQueryBuilder from './lib/PostgrestQueryBuilder'
import PostgrestRpcBuilder from './lib/PostgrestRpcBuilder'
import PostgrestTransformBuilder from './lib/PostgrestTransformBuilder'
export default class PostgrestClient {
url: string
headers: { [key: string]: string }
schema?: string
/**
* Creates a PostgREST client.
*
* @param url URL of the PostgREST endpoint.
* @param headers Custom headers.
* @param schema Postgres schema to switch to.
*/
constructor(
url: string,
{ headers = {}, schema }: { headers?: { [key: string]: string }; schema?: string } = {}
) {
this.url = url
this.headers = headers
this.schema = schema
}
/**
* Authenticates the request with JWT.
*
* @param token The JWT token to use.
*/
auth(token: string): this {
this.headers['Authorization'] = `Bearer ${token}`
return this
}
/**
* Perform a table operation.
*
* @param table The table name to operate on.
*/
from<T = any>(table: string): PostgrestQueryBuilder<T> {
const url = `${this.url}/${table}`
return new PostgrestQueryBuilder<T>(url, { headers: this.headers, schema: this.schema })
}
/**
* Perform a stored procedure call.
*
* @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,
{
count = null,
}: {
count?: null | 'exact' | 'planned' | 'estimated'
} = {}
): PostgrestTransformBuilder<T> {
const url = `${this.url}/rpc/${fn}`
return new PostgrestRpcBuilder<T>(url, {
headers: this.headers,
schema: this.schema,
}).rpc(params, { count })
}
}