Skip to content

Commit 0a2239c

Browse files
chore: make some internal functions async
1 parent 0939a4a commit 0a2239c

2 files changed

Lines changed: 29 additions & 26 deletions

File tree

src/client.ts

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ export class Writer {
262262
* Create a new client instance re-using the same options given to the current client with optional overriding.
263263
*/
264264
withOptions(options: Partial<ClientOptions>): this {
265-
return new (this.constructor as any as new (props: ClientOptions) => typeof this)({
265+
const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({
266266
...this._options,
267267
baseURL: this.baseURL,
268268
maxRetries: this.maxRetries,
@@ -274,6 +274,7 @@ export class Writer {
274274
apiKey: this.apiKey,
275275
...options,
276276
});
277+
return client;
277278
}
278279

279280
/**
@@ -291,7 +292,7 @@ export class Writer {
291292
return;
292293
}
293294

294-
protected authHeaders(opts: FinalRequestOptions): NullableHeaders | undefined {
295+
protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
295296
return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]);
296297
}
297298

@@ -423,7 +424,9 @@ export class Writer {
423424

424425
await this.prepareOptions(options);
425426

426-
const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
427+
const { req, url, timeout } = await this.buildRequest(options, {
428+
retryCount: maxRetries - retriesRemaining,
429+
});
427430

428431
await this.prepareRequest(req, { url, options });
429432

@@ -501,7 +504,7 @@ export class Writer {
501504
} with status ${response.status} in ${headersTime - startTime}ms`;
502505

503506
if (!response.ok) {
504-
const shouldRetry = this.shouldRetry(response);
507+
const shouldRetry = await this.shouldRetry(response);
505508
if (retriesRemaining && shouldRetry) {
506509
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
507510

@@ -619,7 +622,7 @@ export class Writer {
619622
}
620623
}
621624

622-
private shouldRetry(response: Response): boolean {
625+
private async shouldRetry(response: Response): Promise<boolean> {
623626
// Note this is not a standard header.
624627
const shouldRetryHeader = response.headers.get('x-should-retry');
625628

@@ -696,18 +699,18 @@ export class Writer {
696699
return sleepSeconds * jitter * 1000;
697700
}
698701

699-
buildRequest(
702+
async buildRequest(
700703
inputOptions: FinalRequestOptions,
701704
{ retryCount = 0 }: { retryCount?: number } = {},
702-
): { req: FinalizedRequestInit; url: string; timeout: number } {
705+
): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> {
703706
const options = { ...inputOptions };
704707
const { method, path, query, defaultBaseURL } = options;
705708

706709
const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);
707710
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
708711
options.timeout = options.timeout ?? this.timeout;
709712
const { bodyHeaders, body } = this.buildBody({ options });
710-
const reqHeaders = this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
713+
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
711714

712715
const req: FinalizedRequestInit = {
713716
method,
@@ -723,7 +726,7 @@ export class Writer {
723726
return { req, url, timeout: options.timeout };
724727
}
725728

726-
private buildHeaders({
729+
private async buildHeaders({
727730
options,
728731
method,
729732
bodyHeaders,
@@ -733,7 +736,7 @@ export class Writer {
733736
method: HTTPMethod;
734737
bodyHeaders: HeadersLike;
735738
retryCount: number;
736-
}): Headers {
739+
}): Promise<Headers> {
737740
let idempotencyHeaders: HeadersLike = {};
738741
if (this.idempotencyHeader && method !== 'get') {
739742
if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
@@ -749,7 +752,7 @@ export class Writer {
749752
...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
750753
...getPlatformHeaders(),
751754
},
752-
this.authHeaders(options),
755+
await this.authHeaders(options),
753756
this._options.defaultHeaders,
754757
bodyHeaders,
755758
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 },
@@ -344,7 +344,7 @@ describe('instantiate client', () => {
344344
});
345345

346346
describe('withOptions', () => {
347-
test('creates a new client with overridden options', () => {
347+
test('creates a new client with overridden options', async () => {
348348
const client = new Writer({ baseURL: 'http://localhost:5000/', maxRetries: 3, apiKey: 'My API Key' });
349349

350350
const newClient = client.withOptions({
@@ -365,7 +365,7 @@ describe('instantiate client', () => {
365365
expect(newClient.constructor).toBe(client.constructor);
366366
});
367367

368-
test('inherits options from the parent client', () => {
368+
test('inherits options from the parent client', async () => {
369369
const client = new Writer({
370370
baseURL: 'http://localhost:5000/',
371371
defaultHeaders: { 'X-Test-Header': 'test-value' },
@@ -380,7 +380,7 @@ describe('instantiate client', () => {
380380
// Test inherited options remain the same
381381
expect(newClient.buildURL('/foo', null)).toEqual('http://localhost:5001/foo?test-param=test-value');
382382

383-
const { req } = newClient.buildRequest({ path: '/foo', method: 'get' });
383+
const { req } = await newClient.buildRequest({ path: '/foo', method: 'get' });
384384
expect(req.headers.get('x-test-header')).toEqual('test-value');
385385
});
386386

@@ -430,8 +430,8 @@ describe('request building', () => {
430430
const client = new Writer({ apiKey: 'My API Key' });
431431

432432
describe('custom headers', () => {
433-
test('handles undefined', () => {
434-
const { req } = client.buildRequest({
433+
test('handles undefined', async () => {
434+
const { req } = await client.buildRequest({
435435
path: '/foo',
436436
method: 'post',
437437
body: { value: 'hello' },
@@ -466,8 +466,8 @@ describe('default encoder', () => {
466466
}
467467
}
468468
for (const jsonValue of [{}, [], { __proto__: null }, new Serializable(), new Collection(['item'])]) {
469-
test(`serializes ${util.inspect(jsonValue)} as json`, () => {
470-
const { req } = client.buildRequest({
469+
test(`serializes ${util.inspect(jsonValue)} as json`, async () => {
470+
const { req } = await client.buildRequest({
471471
path: '/foo',
472472
method: 'post',
473473
body: jsonValue,
@@ -490,7 +490,7 @@ describe('default encoder', () => {
490490
asyncIterable,
491491
]) {
492492
test(`converts ${util.inspect(streamValue)} to ReadableStream`, async () => {
493-
const { req } = client.buildRequest({
493+
const { req } = await client.buildRequest({
494494
path: '/foo',
495495
method: 'post',
496496
body: streamValue,
@@ -503,7 +503,7 @@ describe('default encoder', () => {
503503
}
504504

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

0 commit comments

Comments
 (0)