-
-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathPostgrestClient.ts
57 lines (52 loc) · 1.5 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
import PostgrestQueryBuilder from './lib/PostgrestQueryBuilder'
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.
*/
rpc<T = any>(fn: string, params?: object): PostgrestTransformBuilder<T> {
const url = `${this.url}/rpc/${fn}`
return new PostgrestQueryBuilder<T>(url, { headers: this.headers, schema: this.schema }).rpc(
params
)
}
}