Skip to content

Commit

Permalink
feat: allow setting headers on a per-call basis
Browse files Browse the repository at this point in the history
  • Loading branch information
soedirgo committed Aug 3, 2024
1 parent 7b5922f commit 9f91e72
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/PostgrestBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ export default abstract class PostgrestBuilder<Result>
return this
}

/**
* Set an HTTP header for the request.
*/
setHeader(name: string, value: string): this {
this.headers = { ...this.headers }
this.headers[name] = value
return this
}

then<TResult1 = PostgrestSingleResponse<Result>, TResult2 = never>(
onfulfilled?:
| ((value: PostgrestSingleResponse<Result>) => TResult1 | PromiseLike<TResult1>)
Expand Down
9 changes: 9 additions & 0 deletions test/basic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,15 @@ test('custom headers', async () => {
expect((postgrest.from('users').select() as any).headers['apikey']).toEqual('foo')
})

test('custom headers on a per-call basis', async () => {
const postgrest1 = new PostgrestClient<Database>(REST_URL, { headers: { apikey: 'foo' } })
const postgrest2 = postgrest1.rpc('void_func').setHeader('apikey', 'bar')
// Original client object isn't affected
expect((postgrest1.from('users').select() as any).headers['apikey']).toEqual('foo')
// Derived client object uses new header value
expect((postgrest2 as any).headers['apikey']).toEqual('bar')
})

describe('custom prefer headers with ', () => {
test('insert', async () => {
const postgrest = new PostgrestClient<Database>(REST_URL, {
Expand Down
9 changes: 9 additions & 0 deletions test/index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,12 @@ const postgrest = new PostgrestClient<Database>(REST_URL)
channels.channel_details
)
}

// PostgrestBuilder's children retains class when using inherited methods
{
const x = postgrest.from('channels').select()
const y = x.throwOnError()
const z = x.setHeader('', '')
expectType<typeof x>(y)
expectType<typeof x>(z)
}

0 comments on commit 9f91e72

Please sign in to comment.