Skip to content

Commit cc8085d

Browse files
chore: make some internal functions async
1 parent bcdc5af commit cc8085d

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
@@ -213,7 +213,7 @@ export class CasParser {
213213
* Create a new client instance re-using the same options given to the current client with optional overriding.
214214
*/
215215
withOptions(options: Partial<ClientOptions>): this {
216-
return new (this.constructor as any as new (props: ClientOptions) => typeof this)({
216+
const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({
217217
...this._options,
218218
environment: options.environment ? options.environment : undefined,
219219
baseURL: options.environment ? undefined : this.baseURL,
@@ -226,6 +226,7 @@ export class CasParser {
226226
apiKey: this.apiKey,
227227
...options,
228228
});
229+
return client;
229230
}
230231

231232
/**
@@ -243,7 +244,7 @@ export class CasParser {
243244
return;
244245
}
245246

246-
protected authHeaders(opts: FinalRequestOptions): NullableHeaders | undefined {
247+
protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
247248
return buildHeaders([{ 'x-api-key': this.apiKey }]);
248249
}
249250

@@ -375,7 +376,9 @@ export class CasParser {
375376

376377
await this.prepareOptions(options);
377378

378-
const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
379+
const { req, url, timeout } = await this.buildRequest(options, {
380+
retryCount: maxRetries - retriesRemaining,
381+
});
379382

380383
await this.prepareRequest(req, { url, options });
381384

@@ -453,7 +456,7 @@ export class CasParser {
453456
} with status ${response.status} in ${headersTime - startTime}ms`;
454457

455458
if (!response.ok) {
456-
const shouldRetry = this.shouldRetry(response);
459+
const shouldRetry = await this.shouldRetry(response);
457460
if (retriesRemaining && shouldRetry) {
458461
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
459462

@@ -552,7 +555,7 @@ export class CasParser {
552555
}
553556
}
554557

555-
private shouldRetry(response: Response): boolean {
558+
private async shouldRetry(response: Response): Promise<boolean> {
556559
// Note this is not a standard header.
557560
const shouldRetryHeader = response.headers.get('x-should-retry');
558561

@@ -629,18 +632,18 @@ export class CasParser {
629632
return sleepSeconds * jitter * 1000;
630633
}
631634

632-
buildRequest(
635+
async buildRequest(
633636
inputOptions: FinalRequestOptions,
634637
{ retryCount = 0 }: { retryCount?: number } = {},
635-
): { req: FinalizedRequestInit; url: string; timeout: number } {
638+
): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> {
636639
const options = { ...inputOptions };
637640
const { method, path, query, defaultBaseURL } = options;
638641

639642
const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);
640643
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
641644
options.timeout = options.timeout ?? this.timeout;
642645
const { bodyHeaders, body } = this.buildBody({ options });
643-
const reqHeaders = this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
646+
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
644647

645648
const req: FinalizedRequestInit = {
646649
method,
@@ -656,7 +659,7 @@ export class CasParser {
656659
return { req, url, timeout: options.timeout };
657660
}
658661

659-
private buildHeaders({
662+
private async buildHeaders({
660663
options,
661664
method,
662665
bodyHeaders,
@@ -666,7 +669,7 @@ export class CasParser {
666669
method: HTTPMethod;
667670
bodyHeaders: HeadersLike;
668671
retryCount: number;
669-
}): Headers {
672+
}): Promise<Headers> {
670673
let idempotencyHeaders: HeadersLike = {};
671674
if (this.idempotencyHeader && method !== 'get') {
672675
if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
@@ -682,7 +685,7 @@ export class CasParser {
682685
...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
683686
...getPlatformHeaders(),
684687
},
685-
this.authHeaders(options),
688+
await this.authHeaders(options),
686689
this._options.defaultHeaders,
687690
bodyHeaders,
688691
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 },
@@ -361,7 +361,7 @@ describe('instantiate client', () => {
361361
});
362362

363363
describe('withOptions', () => {
364-
test('creates a new client with overridden options', () => {
364+
test('creates a new client with overridden options', async () => {
365365
const client = new CasParser({
366366
baseURL: 'http://localhost:5000/',
367367
maxRetries: 3,
@@ -386,7 +386,7 @@ describe('instantiate client', () => {
386386
expect(newClient.constructor).toBe(client.constructor);
387387
});
388388

389-
test('inherits options from the parent client', () => {
389+
test('inherits options from the parent client', async () => {
390390
const client = new CasParser({
391391
baseURL: 'http://localhost:5000/',
392392
defaultHeaders: { 'X-Test-Header': 'test-value' },
@@ -401,7 +401,7 @@ describe('instantiate client', () => {
401401
// Test inherited options remain the same
402402
expect(newClient.buildURL('/foo', null)).toEqual('http://localhost:5001/foo?test-param=test-value');
403403

404-
const { req } = newClient.buildRequest({ path: '/foo', method: 'get' });
404+
const { req } = await newClient.buildRequest({ path: '/foo', method: 'get' });
405405
expect(req.headers.get('x-test-header')).toEqual('test-value');
406406
});
407407

@@ -455,8 +455,8 @@ describe('request building', () => {
455455
const client = new CasParser({ apiKey: 'My API Key' });
456456

457457
describe('custom headers', () => {
458-
test('handles undefined', () => {
459-
const { req } = client.buildRequest({
458+
test('handles undefined', async () => {
459+
const { req } = await client.buildRequest({
460460
path: '/foo',
461461
method: 'post',
462462
body: { value: 'hello' },
@@ -491,8 +491,8 @@ describe('default encoder', () => {
491491
}
492492
}
493493
for (const jsonValue of [{}, [], { __proto__: null }, new Serializable(), new Collection(['item'])]) {
494-
test(`serializes ${util.inspect(jsonValue)} as json`, () => {
495-
const { req } = client.buildRequest({
494+
test(`serializes ${util.inspect(jsonValue)} as json`, async () => {
495+
const { req } = await client.buildRequest({
496496
path: '/foo',
497497
method: 'post',
498498
body: jsonValue,
@@ -515,7 +515,7 @@ describe('default encoder', () => {
515515
asyncIterable,
516516
]) {
517517
test(`converts ${util.inspect(streamValue)} to ReadableStream`, async () => {
518-
const { req } = client.buildRequest({
518+
const { req } = await client.buildRequest({
519519
path: '/foo',
520520
method: 'post',
521521
body: streamValue,
@@ -528,7 +528,7 @@ describe('default encoder', () => {
528528
}
529529

530530
test(`can set content-type for ReadableStream`, async () => {
531-
const { req } = client.buildRequest({
531+
const { req } = await client.buildRequest({
532532
path: '/foo',
533533
method: 'post',
534534
body: new Response('a\nb\nc\n').body,

0 commit comments

Comments
 (0)