Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add request and response interceptors #619

Merged
merged 6 commits into from
May 15, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"license": "Apache-2.0",
"devDependencies": {
"@babel/plugin-proposal-private-methods": "^7.18.6",
"@compodoc/compodoc": "^1.1.9",
"@compodoc/compodoc": "1.1.21",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pinning compodoc because the downstream dep @angular-devkit/schematics appears to have dropped < Node 16 in the latest version which was breaking CI for us.

"@types/cors": "^2.8.6",
"@types/express": "^4.16.1",
"@types/extend": "^3.0.1",
Expand Down
67 changes: 66 additions & 1 deletion src/gaxios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
import {getRetryConfig} from './retry';
import {PassThrough, Stream, pipeline} from 'stream';
import {v4} from 'uuid';
import {GaxiosInterceptorManager} from './interceptor';

/* eslint-disable @typescript-eslint/no-explicit-any */

Expand Down Expand Up @@ -63,6 +64,11 @@ function getHeader(options: GaxiosOptions, header: string): string | undefined {
return undefined;
}

enum GaxiosInterceptorType {
Request = 1,
Response,
}

export class Gaxios {
protected agentCache = new Map<
string | URL,
Expand All @@ -74,12 +80,24 @@ export class Gaxios {
*/
defaults: GaxiosOptions;

/**
* Interceptors
*/
interceptors: {
request: GaxiosInterceptorManager<GaxiosOptions>;
response: GaxiosInterceptorManager<GaxiosResponse>;
};

/**
* The Gaxios class is responsible for making HTTP requests.
* @param defaults The default set of options to be used for this instance.
*/
constructor(defaults?: GaxiosOptions) {
this.defaults = defaults || {};
this.interceptors = {
request: new GaxiosInterceptorManager(),
response: new GaxiosInterceptorManager(),
};
}

/**
Expand All @@ -88,7 +106,11 @@ export class Gaxios {
*/
async request<T = any>(opts: GaxiosOptions = {}): GaxiosPromise<T> {
opts = await this.#prepareRequest(opts);
return this._request(opts);
opts = await this.#applyInterceptors(opts);
return this.#applyInterceptors(
this._request(opts),
GaxiosInterceptorType.Response
);
}

private async _defaultAdapter<T>(
Expand Down Expand Up @@ -230,6 +252,49 @@ export class Gaxios {
return true;
}

/**
* Applies the interceptors. The request interceptors are applied after the
* call to prepareRequest is completed. The response interceptors are applied after the call
* to translateResponse.
*
* @param {T} optionsOrResponse The current set of options or the translated response.
*
* @returns {Promise<T>} Promise that resolves to the set of options or response after interceptors are applied.
*/
async #applyInterceptors<
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than adding GaxiosInterceptorType perhaps we can have separate methods for #applyInterceptors; #applyRequestInterceptors and #applyResponseInterceptors - the logic in #applyInterceptors can be cleanly separated by its if/else condition

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That was what I was originally trying to avoid but now that I think about it, makes more sense, single responsibility and all that. Will adjust.

T extends
| GaxiosOptions
| GaxiosResponse
| Promise<GaxiosOptions | GaxiosResponse>,
>(
optionsOrResponse: T,
type: GaxiosInterceptorType = GaxiosInterceptorType.Request
): Promise<T> {
let promiseChain = Promise.resolve(optionsOrResponse) as Promise<T>;

if (type === GaxiosInterceptorType.Request) {
for (const interceptor of this.interceptors.request) {
if (interceptor) {
promiseChain = promiseChain.then(
interceptor.resolved as unknown as (opts: T) => Promise<T>,
interceptor.rejected
) as Promise<T>;
}
}
} else {
for (const interceptor of this.interceptors.response) {
if (interceptor) {
promiseChain = promiseChain.then(
interceptor.resolved as unknown as (resp: T) => Promise<T>,
interceptor.rejected
) as Promise<T>;
}
}
}

return promiseChain;
}

/**
* Validates the options, merges them with defaults, and prepare request.
*
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export {
RetryConfig,
} from './common';
export {Gaxios, GaxiosOptions};
export * from './interceptor';

/**
* The default instance used when the `request` method is directly
Expand Down
104 changes: 104 additions & 0 deletions src/interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright 2024 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {GaxiosError, GaxiosOptions, GaxiosResponse} from './common';

/**
* Interceptors that can be run for requests or responses. These interceptors run asynchronously.
*/
export interface GaxiosInterceptor<T extends GaxiosOptions | GaxiosResponse> {
/**
* Function to be run when applying an interceptor.
*
* @param {T} configOrResponse The current configuration or response.
* @returns {Promise<T>} Promise that resolves to the modified set of options or response.
*/
resolved?: (configOrResponse: T) => Promise<T>;
/**
* Function to be run if the previous call to resolved throws / rejects or the request results in an invalid status
* as determined by the call to validateStatus.
*
* @param {GaxiosError} err The error thrown from the previously called resolved function.
*/
rejected?: (err: GaxiosError) => void;
}

/**
* Class to manage collections of GaxiosInterceptors for both requests and responses.
*/
export class GaxiosInterceptorManager<T extends GaxiosOptions | GaxiosResponse>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are the benefits of GaxiosInterceptorManager over a Map? They are also ordered by insertion.

Copy link
Contributor Author

@ddelgrosso1 ddelgrosso1 May 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I keep forgetting that JavaScript maps behave like that.

Copy link
Contributor Author

@ddelgrosso1 ddelgrosso1 May 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The additional benefit of using a class is that we don't have to add functions to Gaxios.ts to add, remove, clear interceptors. It keeps things a bit more separated that way.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplified the class to use maps under the hood. Kept it wrapped in a class just to keep the logic from seeping into Gaxios.ts

implements
Iterator<GaxiosInterceptor<T> | null>,
Iterable<GaxiosInterceptor<T> | null>
{
#interceptorQueue: Array<GaxiosInterceptor<T> | null>;
#index: number;

constructor() {
this.#interceptorQueue = [];
this.#index = 0;
}

[Symbol.iterator](): Iterator<GaxiosInterceptor<T> | null> {
return this;
}

next(): IteratorResult<
GaxiosInterceptor<T> | null,
GaxiosInterceptor<T> | null
> {
const value =
this.#index < this.#interceptorQueue.length
? this.#interceptorQueue[this.#index]
: undefined;

return this.#index++ >= this.#interceptorQueue.length
? ({
done: true,
value,
} as IteratorReturnResult<GaxiosInterceptor<T> | null>)
: ({
done: false,
value,
} as IteratorYieldResult<GaxiosInterceptor<T> | null>);
}

/**
* Adds an interceptor to the queue.
*
* @param {GaxiosInterceptor} interceptor the interceptor to be added.
*
* @returns {number} an identifier that can be used to remove the interceptor.
*/
addInterceptor(interceptor: GaxiosInterceptor<T>): number {
return this.#interceptorQueue.push(interceptor) - 1;
}

/**
* Removes an interceptor from the queue.
*
* @param {number} id the previously id of the interceptor to remove.
*/
removeInterceptor(id: number) {
if (this.#interceptorQueue[id]) {
this.#interceptorQueue[id] = null;
}
}

/**
* Removes all interceptors from the queue.
*/
removeAll() {
this.#interceptorQueue = [];
}
}
Loading
Loading