Skip to content

Commit 9f91e72

Browse files
committed
feat: allow setting headers on a per-call basis
1 parent 7b5922f commit 9f91e72

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

src/PostgrestBuilder.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,15 @@ export default abstract class PostgrestBuilder<Result>
4747
return this
4848
}
4949

50+
/**
51+
* Set an HTTP header for the request.
52+
*/
53+
setHeader(name: string, value: string): this {
54+
this.headers = { ...this.headers }
55+
this.headers[name] = value
56+
return this
57+
}
58+
5059
then<TResult1 = PostgrestSingleResponse<Result>, TResult2 = never>(
5160
onfulfilled?:
5261
| ((value: PostgrestSingleResponse<Result>) => TResult1 | PromiseLike<TResult1>)

test/basic.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,15 @@ test('custom headers', async () => {
107107
expect((postgrest.from('users').select() as any).headers['apikey']).toEqual('foo')
108108
})
109109

110+
test('custom headers on a per-call basis', async () => {
111+
const postgrest1 = new PostgrestClient<Database>(REST_URL, { headers: { apikey: 'foo' } })
112+
const postgrest2 = postgrest1.rpc('void_func').setHeader('apikey', 'bar')
113+
// Original client object isn't affected
114+
expect((postgrest1.from('users').select() as any).headers['apikey']).toEqual('foo')
115+
// Derived client object uses new header value
116+
expect((postgrest2 as any).headers['apikey']).toEqual('bar')
117+
})
118+
110119
describe('custom prefer headers with ', () => {
111120
test('insert', async () => {
112121
const postgrest = new PostgrestClient<Database>(REST_URL, {

test/index.test-d.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,3 +196,12 @@ const postgrest = new PostgrestClient<Database>(REST_URL)
196196
channels.channel_details
197197
)
198198
}
199+
200+
// PostgrestBuilder's children retains class when using inherited methods
201+
{
202+
const x = postgrest.from('channels').select()
203+
const y = x.throwOnError()
204+
const z = x.setHeader('', '')
205+
expectType<typeof x>(y)
206+
expectType<typeof x>(z)
207+
}

0 commit comments

Comments
 (0)