Skip to content

Commit d14a6a0

Browse files
chore: make some internal functions async
1 parent 5673bd9 commit d14a6a0

File tree

2 files changed

+29
-26
lines changed

2 files changed

+29
-26
lines changed

src/client.ts

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ export class Flowglad {
292292
* Create a new client instance re-using the same options given to the current client with optional overriding.
293293
*/
294294
withOptions(options: Partial<ClientOptions>): this {
295-
return new (this.constructor as any as new (props: ClientOptions) => typeof this)({
295+
const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({
296296
...this._options,
297297
baseURL: this.baseURL,
298298
maxRetries: this.maxRetries,
@@ -304,6 +304,7 @@ export class Flowglad {
304304
apiKey: this.apiKey,
305305
...options,
306306
});
307+
return client;
307308
}
308309

309310
/**
@@ -321,7 +322,7 @@ export class Flowglad {
321322
return;
322323
}
323324

324-
protected authHeaders(opts: FinalRequestOptions): NullableHeaders | undefined {
325+
protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
325326
return buildHeaders([{ Authorization: this.apiKey }]);
326327
}
327328

@@ -453,7 +454,9 @@ export class Flowglad {
453454

454455
await this.prepareOptions(options);
455456

456-
const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
457+
const { req, url, timeout } = await this.buildRequest(options, {
458+
retryCount: maxRetries - retriesRemaining,
459+
});
457460

458461
await this.prepareRequest(req, { url, options });
459462

@@ -531,7 +534,7 @@ export class Flowglad {
531534
} with status ${response.status} in ${headersTime - startTime}ms`;
532535

533536
if (!response.ok) {
534-
const shouldRetry = this.shouldRetry(response);
537+
const shouldRetry = await this.shouldRetry(response);
535538
if (retriesRemaining && shouldRetry) {
536539
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
537540

@@ -630,7 +633,7 @@ export class Flowglad {
630633
}
631634
}
632635

633-
private shouldRetry(response: Response): boolean {
636+
private async shouldRetry(response: Response): Promise<boolean> {
634637
// Note this is not a standard header.
635638
const shouldRetryHeader = response.headers.get('x-should-retry');
636639

@@ -707,18 +710,18 @@ export class Flowglad {
707710
return sleepSeconds * jitter * 1000;
708711
}
709712

710-
buildRequest(
713+
async buildRequest(
711714
inputOptions: FinalRequestOptions,
712715
{ retryCount = 0 }: { retryCount?: number } = {},
713-
): { req: FinalizedRequestInit; url: string; timeout: number } {
716+
): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> {
714717
const options = { ...inputOptions };
715718
const { method, path, query, defaultBaseURL } = options;
716719

717720
const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);
718721
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
719722
options.timeout = options.timeout ?? this.timeout;
720723
const { bodyHeaders, body } = this.buildBody({ options });
721-
const reqHeaders = this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
724+
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
722725

723726
const req: FinalizedRequestInit = {
724727
method,
@@ -734,7 +737,7 @@ export class Flowglad {
734737
return { req, url, timeout: options.timeout };
735738
}
736739

737-
private buildHeaders({
740+
private async buildHeaders({
738741
options,
739742
method,
740743
bodyHeaders,
@@ -744,7 +747,7 @@ export class Flowglad {
744747
method: HTTPMethod;
745748
bodyHeaders: HeadersLike;
746749
retryCount: number;
747-
}): Headers {
750+
}): Promise<Headers> {
748751
let idempotencyHeaders: HeadersLike = {};
749752
if (this.idempotencyHeader && method !== 'get') {
750753
if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
@@ -760,7 +763,7 @@ export class Flowglad {
760763
...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
761764
...getPlatformHeaders(),
762765
},
763-
this.authHeaders(options),
766+
await this.authHeaders(options),
764767
this._options.defaultHeaders,
765768
bodyHeaders,
766769
options.headers,

tests/index.test.ts

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,22 +26,22 @@ describe('instantiate client', () => {
2626
apiKey: 'My API Key',
2727
});
2828

29-
test('they are used in the request', () => {
30-
const { req } = client.buildRequest({ path: '/foo', method: 'post' });
29+
test('they are used in the request', async () => {
30+
const { req } = await client.buildRequest({ path: '/foo', method: 'post' });
3131
expect(req.headers.get('x-my-default-header')).toEqual('2');
3232
});
3333

34-
test('can ignore `undefined` and leave the default', () => {
35-
const { req } = client.buildRequest({
34+
test('can ignore `undefined` and leave the default', async () => {
35+
const { req } = await client.buildRequest({
3636
path: '/foo',
3737
method: 'post',
3838
headers: { 'X-My-Default-Header': undefined },
3939
});
4040
expect(req.headers.get('x-my-default-header')).toEqual('2');
4141
});
4242

43-
test('can be removed with `null`', () => {
44-
const { req } = client.buildRequest({
43+
test('can be removed with `null`', async () => {
44+
const { req } = await client.buildRequest({
4545
path: '/foo',
4646
method: 'post',
4747
headers: { 'X-My-Default-Header': null },
@@ -348,7 +348,7 @@ describe('instantiate client', () => {
348348
});
349349

350350
describe('withOptions', () => {
351-
test('creates a new client with overridden options', () => {
351+
test('creates a new client with overridden options', async () => {
352352
const client = new Flowglad({ baseURL: 'http://localhost:5000/', maxRetries: 3, apiKey: 'My API Key' });
353353

354354
const newClient = client.withOptions({
@@ -369,7 +369,7 @@ describe('instantiate client', () => {
369369
expect(newClient.constructor).toBe(client.constructor);
370370
});
371371

372-
test('inherits options from the parent client', () => {
372+
test('inherits options from the parent client', async () => {
373373
const client = new Flowglad({
374374
baseURL: 'http://localhost:5000/',
375375
defaultHeaders: { 'X-Test-Header': 'test-value' },
@@ -384,7 +384,7 @@ describe('instantiate client', () => {
384384
// Test inherited options remain the same
385385
expect(newClient.buildURL('/foo', null)).toEqual('http://localhost:5001/foo?test-param=test-value');
386386

387-
const { req } = newClient.buildRequest({ path: '/foo', method: 'get' });
387+
const { req } = await newClient.buildRequest({ path: '/foo', method: 'get' });
388388
expect(req.headers.get('x-test-header')).toEqual('test-value');
389389
});
390390

@@ -434,8 +434,8 @@ describe('request building', () => {
434434
const client = new Flowglad({ apiKey: 'My API Key' });
435435

436436
describe('custom headers', () => {
437-
test('handles undefined', () => {
438-
const { req } = client.buildRequest({
437+
test('handles undefined', async () => {
438+
const { req } = await client.buildRequest({
439439
path: '/foo',
440440
method: 'post',
441441
body: { value: 'hello' },
@@ -470,8 +470,8 @@ describe('default encoder', () => {
470470
}
471471
}
472472
for (const jsonValue of [{}, [], { __proto__: null }, new Serializable(), new Collection(['item'])]) {
473-
test(`serializes ${util.inspect(jsonValue)} as json`, () => {
474-
const { req } = client.buildRequest({
473+
test(`serializes ${util.inspect(jsonValue)} as json`, async () => {
474+
const { req } = await client.buildRequest({
475475
path: '/foo',
476476
method: 'post',
477477
body: jsonValue,
@@ -494,7 +494,7 @@ describe('default encoder', () => {
494494
asyncIterable,
495495
]) {
496496
test(`converts ${util.inspect(streamValue)} to ReadableStream`, async () => {
497-
const { req } = client.buildRequest({
497+
const { req } = await client.buildRequest({
498498
path: '/foo',
499499
method: 'post',
500500
body: streamValue,
@@ -507,7 +507,7 @@ describe('default encoder', () => {
507507
}
508508

509509
test(`can set content-type for ReadableStream`, async () => {
510-
const { req } = client.buildRequest({
510+
const { req } = await client.buildRequest({
511511
path: '/foo',
512512
method: 'post',
513513
body: new Response('a\nb\nc\n').body,

0 commit comments

Comments
 (0)