Skip to content

Commit 4f16312

Browse files
chore: make some internal functions async
1 parent a197e2f commit 4f16312

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
@@ -200,7 +200,7 @@ export class Grid {
200200
* Create a new client instance re-using the same options given to the current client with optional overriding.
201201
*/
202202
withOptions(options: Partial<ClientOptions>): this {
203-
return new (this.constructor as any as new (props: ClientOptions) => typeof this)({
203+
const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({
204204
...this._options,
205205
baseURL: this.baseURL,
206206
maxRetries: this.maxRetries,
@@ -212,6 +212,7 @@ export class Grid {
212212
apiKey: this.apiKey,
213213
...options,
214214
});
215+
return client;
215216
}
216217

217218
/**
@@ -229,7 +230,7 @@ export class Grid {
229230
return;
230231
}
231232

232-
protected authHeaders(opts: FinalRequestOptions): NullableHeaders | undefined {
233+
protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
233234
return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]);
234235
}
235236

@@ -361,7 +362,9 @@ export class Grid {
361362

362363
await this.prepareOptions(options);
363364

364-
const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
365+
const { req, url, timeout } = await this.buildRequest(options, {
366+
retryCount: maxRetries - retriesRemaining,
367+
});
365368

366369
await this.prepareRequest(req, { url, options });
367370

@@ -439,7 +442,7 @@ export class Grid {
439442
} with status ${response.status} in ${headersTime - startTime}ms`;
440443

441444
if (!response.ok) {
442-
const shouldRetry = this.shouldRetry(response);
445+
const shouldRetry = await this.shouldRetry(response);
443446
if (retriesRemaining && shouldRetry) {
444447
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
445448

@@ -557,7 +560,7 @@ export class Grid {
557560
}
558561
}
559562

560-
private shouldRetry(response: Response): boolean {
563+
private async shouldRetry(response: Response): Promise<boolean> {
561564
// Note this is not a standard header.
562565
const shouldRetryHeader = response.headers.get('x-should-retry');
563566

@@ -634,18 +637,18 @@ export class Grid {
634637
return sleepSeconds * jitter * 1000;
635638
}
636639

637-
buildRequest(
640+
async buildRequest(
638641
inputOptions: FinalRequestOptions,
639642
{ retryCount = 0 }: { retryCount?: number } = {},
640-
): { req: FinalizedRequestInit; url: string; timeout: number } {
643+
): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> {
641644
const options = { ...inputOptions };
642645
const { method, path, query, defaultBaseURL } = options;
643646

644647
const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);
645648
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
646649
options.timeout = options.timeout ?? this.timeout;
647650
const { bodyHeaders, body } = this.buildBody({ options });
648-
const reqHeaders = this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
651+
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
649652

650653
const req: FinalizedRequestInit = {
651654
method,
@@ -661,7 +664,7 @@ export class Grid {
661664
return { req, url, timeout: options.timeout };
662665
}
663666

664-
private buildHeaders({
667+
private async buildHeaders({
665668
options,
666669
method,
667670
bodyHeaders,
@@ -671,7 +674,7 @@ export class Grid {
671674
method: HTTPMethod;
672675
bodyHeaders: HeadersLike;
673676
retryCount: number;
674-
}): Headers {
677+
}): Promise<Headers> {
675678
let idempotencyHeaders: HeadersLike = {};
676679
if (this.idempotencyHeader && method !== 'get') {
677680
if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
@@ -688,7 +691,7 @@ export class Grid {
688691
...getPlatformHeaders(),
689692
'X-Client-Name': 'api-sdk',
690693
},
691-
this.authHeaders(options),
694+
await this.authHeaders(options),
692695
this._options.defaultHeaders,
693696
bodyHeaders,
694697
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 },
@@ -340,7 +340,7 @@ describe('instantiate client', () => {
340340
});
341341

342342
describe('withOptions', () => {
343-
test('creates a new client with overridden options', () => {
343+
test('creates a new client with overridden options', async () => {
344344
const client = new Grid({ baseURL: 'http://localhost:5000/', maxRetries: 3, apiKey: 'My API Key' });
345345

346346
const newClient = client.withOptions({
@@ -361,7 +361,7 @@ describe('instantiate client', () => {
361361
expect(newClient.constructor).toBe(client.constructor);
362362
});
363363

364-
test('inherits options from the parent client', () => {
364+
test('inherits options from the parent client', async () => {
365365
const client = new Grid({
366366
baseURL: 'http://localhost:5000/',
367367
defaultHeaders: { 'X-Test-Header': 'test-value' },
@@ -376,7 +376,7 @@ describe('instantiate client', () => {
376376
// Test inherited options remain the same
377377
expect(newClient.buildURL('/foo', null)).toEqual('http://localhost:5001/foo?test-param=test-value');
378378

379-
const { req } = newClient.buildRequest({ path: '/foo', method: 'get' });
379+
const { req } = await newClient.buildRequest({ path: '/foo', method: 'get' });
380380
expect(req.headers.get('x-test-header')).toEqual('test-value');
381381
});
382382

@@ -426,8 +426,8 @@ describe('request building', () => {
426426
const client = new Grid({ apiKey: 'My API Key' });
427427

428428
describe('custom headers', () => {
429-
test('handles undefined', () => {
430-
const { req } = client.buildRequest({
429+
test('handles undefined', async () => {
430+
const { req } = await client.buildRequest({
431431
path: '/foo',
432432
method: 'post',
433433
body: { value: 'hello' },
@@ -462,8 +462,8 @@ describe('default encoder', () => {
462462
}
463463
}
464464
for (const jsonValue of [{}, [], { __proto__: null }, new Serializable(), new Collection(['item'])]) {
465-
test(`serializes ${util.inspect(jsonValue)} as json`, () => {
466-
const { req } = client.buildRequest({
465+
test(`serializes ${util.inspect(jsonValue)} as json`, async () => {
466+
const { req } = await client.buildRequest({
467467
path: '/foo',
468468
method: 'post',
469469
body: jsonValue,
@@ -486,7 +486,7 @@ describe('default encoder', () => {
486486
asyncIterable,
487487
]) {
488488
test(`converts ${util.inspect(streamValue)} to ReadableStream`, async () => {
489-
const { req } = client.buildRequest({
489+
const { req } = await client.buildRequest({
490490
path: '/foo',
491491
method: 'post',
492492
body: streamValue,
@@ -499,7 +499,7 @@ describe('default encoder', () => {
499499
}
500500

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

0 commit comments

Comments
 (0)