Skip to content
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
16 changes: 16 additions & 0 deletions src/blutui.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,22 @@ describe('Blutui', () => {
})
})

describe('when access token and fetch function are provided to the constructor', () => {
it('initalizes', async () => {
// Example from JWT.io
const token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
expect(
() =>
new Blutui(token, {
request: {
fetch: fetch,
},
})
).not.toThrow()
})
})

describe('version', () => {
it('matches the version in `package.json`', async () => {
const blutui = new Blutui('eyJhbGciOi')
Expand Down
14 changes: 9 additions & 5 deletions src/blutui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,16 @@ export class Blutui {

const useAgent: string = `blutui-node/${VERSION}`

this.client = new Client(this.baseURL, {
headers: {
Authorization: `Bearer ${this.accessToken}`,
'User-Agent': useAgent,
this.client = new Client(
this.baseURL,
{
headers: {
Authorization: `Bearer ${this.accessToken}`,
'User-Agent': useAgent,
},
},
})
options.request?.fetch
)
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
export interface BlutuiOptions {
apiHostname?: string
request?: {
fetch?: typeof fetch
// biome-ignore lint/suspicious/noExplicitAny: We want developers to be able to use node-fetch
fetch?: any
}
}

Expand Down
20 changes: 17 additions & 3 deletions src/utils/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,24 @@ import { FetchException } from '../exceptions'
const API_VERSION = 'v1'

export class Client {
private readonly _fetchFn

/**
* Create a new client instance.
*/
constructor(
readonly baseURL: string,
readonly options?: RequestInit
) {}
readonly options?: RequestInit,
fetchFn?: typeof fetch
) {
this._fetchFn = fetchFn || globalThis.fetch

if (!this._fetchFn) {
throw new Error(
'Fetch function not defined in the global scope and no replacement was provided.'
)
}
}

async get(
path: string,
Expand Down Expand Up @@ -80,7 +94,7 @@ export class Client {
}

private async fetch(url: string, options?: RequestInit) {
const response = await fetch(url, {
const response = await this._fetchFn(url, {
...this.options,
...options,
headers: {
Expand Down