-
Notifications
You must be signed in to change notification settings - Fork 58
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
Changes from 2 commits
c21f3b3
555c716
1dbcf38
14e4077
a7a2ebf
09bd538
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 */ | ||
|
||
|
@@ -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, | ||
|
@@ -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(), | ||
}; | ||
} | ||
|
||
/** | ||
|
@@ -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>( | ||
|
@@ -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< | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Rather than adding There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. | ||
* | ||
|
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> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What are the benefits of There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I keep forgetting that JavaScript maps behave like that. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 = []; | ||
} | ||
} |
There was a problem hiding this comment.
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.