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 5 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
66 changes: 65 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 @@ -74,12 +75,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 +101,8 @@ export class Gaxios {
*/
async request<T = any>(opts: GaxiosOptions = {}): GaxiosPromise<T> {
opts = await this.#prepareRequest(opts);
return this._request(opts);
opts = await this.#applyRequestInterceptors(opts);
return this.#applyResponseInterceptors(this._request(opts));
}

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

/**
* Applies the request interceptors. The request interceptors are applied after the
* call to prepareRequest is completed.
*
* @param {GaxiosOptions} options The current set of options.
*
* @returns {Promise<GaxiosOptions>} Promise that resolves to the set of options or response after interceptors are applied.
*/
async #applyRequestInterceptors(
options: GaxiosOptions
): Promise<GaxiosOptions> {
let promiseChain = Promise.resolve(options);

for (const interceptor of this.interceptors.request.interceptorMap.values()) {
if (interceptor) {
promiseChain = promiseChain.then(
interceptor.resolved,
interceptor.rejected
) as Promise<GaxiosOptions>;
}
}

return promiseChain;
}

/**
* Applies the response interceptors. The response interceptors are applied after the
* call to request is made.
*
* @param {GaxiosOptions} options The current set of options.
*
* @returns {Promise<GaxiosOptions>} Promise that resolves to the set of options or response after interceptors are applied.
*/
async #applyResponseInterceptors(
response: GaxiosResponse | Promise<GaxiosResponse>
) {
let promiseChain = Promise.resolve(response);

for (const interceptor of this.interceptors.response.interceptorMap.values()) {
if (interceptor) {
promiseChain = promiseChain.then(
interceptor.resolved,
interceptor.rejected
) as Promise<GaxiosResponse>;
}
}

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
79 changes: 79 additions & 0 deletions src/interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// 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,
> {
interceptorMap: Map<Number, GaxiosInterceptor<T> | null>;

constructor() {
this.interceptorMap = new Map<Number, GaxiosInterceptor<T>>();
}

/**
* Adds an interceptor.
*
* @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 {
const index = this.interceptorMap.size;
this.interceptorMap.set(index, interceptor);

return index;
}

/**
* Removes an interceptor.
*
* @param {number} id the previously id of the interceptor to remove.
*/
removeInterceptor(id: number) {
if (this.interceptorMap.has(id)) {
this.interceptorMap.set(id, null);
}
}

/**
* Removes all interceptors.
*/
removeAll() {
this.interceptorMap.clear();
}
}
Copy link
Member

@danielbankhead danielbankhead May 14, 2024

Choose a reason for hiding this comment

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

[completely optional]: Actually, I'm realizing a Set might be better here than a Map. Sets are also kept in insertion order and the API is 1:1:

  • addInterceptor() -> add()
  • removeInterceptor(number) -> delete(function) (might be easier for customers to find/remove)
  • removeAll -> clear
Suggested change
export class GaxiosInterceptorManager<
T extends GaxiosOptions | GaxiosResponse,
> {
interceptorMap: Map<Number, GaxiosInterceptor<T> | null>;
constructor() {
this.interceptorMap = new Map<Number, GaxiosInterceptor<T>>();
}
/**
* Adds an interceptor.
*
* @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 {
const index = this.interceptorMap.size;
this.interceptorMap.set(index, interceptor);
return index;
}
/**
* Removes an interceptor.
*
* @param {number} id the previously id of the interceptor to remove.
*/
removeInterceptor(id: number) {
if (this.interceptorMap.has(id)) {
this.interceptorMap.set(id, null);
}
}
/**
* Removes all interceptors.
*/
removeAll() {
this.interceptorMap.clear();
}
}
export class GaxiosInterceptorManager<
T extends GaxiosOptions | GaxiosResponse,
> extends Set<GaxiosInterceptor<T> | null> {}

And as feats are added to the Set we can get new stuff for free, like this handy difference method:

Loading
Loading