@microsoft/kiota-http-fetchlibrary
Version:
Kiota request adapter implementation with fetch
56 lines • 2.67 kB
JavaScript
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { CustomFetchHandler } from "./middlewares/customFetchHandler.js";
import { MiddlewareFactory } from "./index.js";
export class HttpClient {
/**
*
* Creates an instance of a HttpClient which contains the middlewares and fetch implementation for request execution.
* @param customFetch - custom fetch function - a Fetch API implementation
* @param middlewares - an array of Middleware handlers
*/
constructor(customFetch, ...middlewares) {
this.customFetch = customFetch;
// If no middlewares are provided, use the default ones
middlewares = (middlewares === null || middlewares === void 0 ? void 0 : middlewares.length) && middlewares[0] ? middlewares : MiddlewareFactory.getDefaultMiddlewares(customFetch);
// If a custom fetch function is provided, add a CustomFetchHandler to the end of the middleware chain
if (this.customFetch) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
middlewares.push(new CustomFetchHandler(customFetch));
}
// Set the middleware handlers chain
this.setMiddleware(...middlewares);
}
/**
* Processes the middleware parameter passed to set this.middleware property
* The calling function should validate if middleware is not undefined or not empty.
* @param middleware - The middleware passed
*/
setMiddleware(...middleware) {
for (let i = 0; i < middleware.length - 1; i++) {
middleware[i].next = middleware[i + 1];
}
this.middleware = middleware[0];
}
/**
* Executes a request and returns a promise resolving the response.
* @param url the request url.
* @param requestInit the RequestInit object.
* @param requestOptions the request options.
* @returns the promise resolving the response.
*/
async executeFetch(url, requestInit, requestOptions) {
if (this.middleware) {
return await this.middleware.execute(url, requestInit, requestOptions);
}
else if (this.customFetch) {
return this.customFetch(url, requestInit);
}
throw new Error("Please provide middlewares or a custom fetch function to execute the request");
}
}
//# sourceMappingURL=httpClient.js.map