Skip to content

Commit b5d654f

Browse files
chore: make some internal functions async
1 parent 9b18738 commit b5d654f

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
@@ -230,7 +230,7 @@ export class Kernel {
230230
* Create a new client instance re-using the same options given to the current client with optional overriding.
231231
*/
232232
withOptions(options: Partial<ClientOptions>): this {
233-
return new (this.constructor as any as new (props: ClientOptions) => typeof this)({
233+
const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({
234234
...this._options,
235235
environment: options.environment ? options.environment : undefined,
236236
baseURL: options.environment ? undefined : this.baseURL,
@@ -243,6 +243,7 @@ export class Kernel {
243243
apiKey: this.apiKey,
244244
...options,
245245
});
246+
return client;
246247
}
247248

248249
/**
@@ -260,7 +261,7 @@ export class Kernel {
260261
return;
261262
}
262263

263-
protected authHeaders(opts: FinalRequestOptions): NullableHeaders | undefined {
264+
protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
264265
return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]);
265266
}
266267

@@ -392,7 +393,9 @@ export class Kernel {
392393

393394
await this.prepareOptions(options);
394395

395-
const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
396+
const { req, url, timeout } = await this.buildRequest(options, {
397+
retryCount: maxRetries - retriesRemaining,
398+
});
396399

397400
await this.prepareRequest(req, { url, options });
398401

@@ -470,7 +473,7 @@ export class Kernel {
470473
} with status ${response.status} in ${headersTime - startTime}ms`;
471474

472475
if (!response.ok) {
473-
const shouldRetry = this.shouldRetry(response);
476+
const shouldRetry = await this.shouldRetry(response);
474477
if (retriesRemaining && shouldRetry) {
475478
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
476479

@@ -569,7 +572,7 @@ export class Kernel {
569572
}
570573
}
571574

572-
private shouldRetry(response: Response): boolean {
575+
private async shouldRetry(response: Response): Promise<boolean> {
573576
// Note this is not a standard header.
574577
const shouldRetryHeader = response.headers.get('x-should-retry');
575578

@@ -646,18 +649,18 @@ export class Kernel {
646649
return sleepSeconds * jitter * 1000;
647650
}
648651

649-
buildRequest(
652+
async buildRequest(
650653
inputOptions: FinalRequestOptions,
651654
{ retryCount = 0 }: { retryCount?: number } = {},
652-
): { req: FinalizedRequestInit; url: string; timeout: number } {
655+
): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> {
653656
const options = { ...inputOptions };
654657
const { method, path, query, defaultBaseURL } = options;
655658

656659
const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);
657660
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
658661
options.timeout = options.timeout ?? this.timeout;
659662
const { bodyHeaders, body } = this.buildBody({ options });
660-
const reqHeaders = this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
663+
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
661664

662665
const req: FinalizedRequestInit = {
663666
method,
@@ -673,7 +676,7 @@ export class Kernel {
673676
return { req, url, timeout: options.timeout };
674677
}
675678

676-
private buildHeaders({
679+
private async buildHeaders({
677680
options,
678681
method,
679682
bodyHeaders,
@@ -683,7 +686,7 @@ export class Kernel {
683686
method: HTTPMethod;
684687
bodyHeaders: HeadersLike;
685688
retryCount: number;
686-
}): Headers {
689+
}): Promise<Headers> {
687690
let idempotencyHeaders: HeadersLike = {};
688691
if (this.idempotencyHeader && method !== 'get') {
689692
if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
@@ -699,7 +702,7 @@ export class Kernel {
699702
...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
700703
...getPlatformHeaders(),
701704
},
702-
this.authHeaders(options),
705+
await this.authHeaders(options),
703706
this._options.defaultHeaders,
704707
bodyHeaders,
705708
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 },
@@ -357,7 +357,7 @@ describe('instantiate client', () => {
357357
});
358358

359359
describe('withOptions', () => {
360-
test('creates a new client with overridden options', () => {
360+
test('creates a new client with overridden options', async () => {
361361
const client = new Kernel({ baseURL: 'http://localhost:5000/', maxRetries: 3, apiKey: 'My API Key' });
362362

363363
const newClient = client.withOptions({
@@ -378,7 +378,7 @@ describe('instantiate client', () => {
378378
expect(newClient.constructor).toBe(client.constructor);
379379
});
380380

381-
test('inherits options from the parent client', () => {
381+
test('inherits options from the parent client', async () => {
382382
const client = new Kernel({
383383
baseURL: 'http://localhost:5000/',
384384
defaultHeaders: { 'X-Test-Header': 'test-value' },
@@ -393,7 +393,7 @@ describe('instantiate client', () => {
393393
// Test inherited options remain the same
394394
expect(newClient.buildURL('/foo', null)).toEqual('http://localhost:5001/foo?test-param=test-value');
395395

396-
const { req } = newClient.buildRequest({ path: '/foo', method: 'get' });
396+
const { req } = await newClient.buildRequest({ path: '/foo', method: 'get' });
397397
expect(req.headers.get('x-test-header')).toEqual('test-value');
398398
});
399399

@@ -443,8 +443,8 @@ describe('request building', () => {
443443
const client = new Kernel({ apiKey: 'My API Key' });
444444

445445
describe('custom headers', () => {
446-
test('handles undefined', () => {
447-
const { req } = client.buildRequest({
446+
test('handles undefined', async () => {
447+
const { req } = await client.buildRequest({
448448
path: '/foo',
449449
method: 'post',
450450
body: { value: 'hello' },
@@ -479,8 +479,8 @@ describe('default encoder', () => {
479479
}
480480
}
481481
for (const jsonValue of [{}, [], { __proto__: null }, new Serializable(), new Collection(['item'])]) {
482-
test(`serializes ${util.inspect(jsonValue)} as json`, () => {
483-
const { req } = client.buildRequest({
482+
test(`serializes ${util.inspect(jsonValue)} as json`, async () => {
483+
const { req } = await client.buildRequest({
484484
path: '/foo',
485485
method: 'post',
486486
body: jsonValue,
@@ -503,7 +503,7 @@ describe('default encoder', () => {
503503
asyncIterable,
504504
]) {
505505
test(`converts ${util.inspect(streamValue)} to ReadableStream`, async () => {
506-
const { req } = client.buildRequest({
506+
const { req } = await client.buildRequest({
507507
path: '/foo',
508508
method: 'post',
509509
body: streamValue,
@@ -516,7 +516,7 @@ describe('default encoder', () => {
516516
}
517517

518518
test(`can set content-type for ReadableStream`, async () => {
519-
const { req } = client.buildRequest({
519+
const { req } = await client.buildRequest({
520520
path: '/foo',
521521
method: 'post',
522522
body: new Response('a\nb\nc\n').body,

0 commit comments

Comments
 (0)