This is an automated email from the ASF dual-hosted git repository.
potiuk pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new e11d8b6382c fix(ui): rebuild ts assets (#51911)
e11d8b6382c is described below
commit e11d8b6382cd6a3f4ff29806c402c8508294aa2f
Author: Wei Lee <[email protected]>
AuthorDate: Thu Jun 19 13:38:15 2025 +0800
fix(ui): rebuild ts assets (#51911)
* fix(ui): rebuild ts assets
* build(pre-commit): ignore ^airflow-core/src/airflow/ui/openapi-gen in
replace-bad-characters
---
.pre-commit-config.yaml | 2 +-
.../ui/openapi-gen/requests/core/ApiError.ts | 28 +-
.../openapi-gen/requests/core/ApiRequestOptions.ts | 38 +-
.../ui/openapi-gen/requests/core/ApiResult.ts | 10 +-
.../openapi-gen/requests/core/CancelablePromise.ts | 234 ++++-----
.../ui/openapi-gen/requests/core/OpenAPI.ts | 52 +-
.../ui/openapi-gen/requests/core/request.ts | 552 ++++++++++-----------
7 files changed, 458 insertions(+), 458 deletions(-)
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index abc7b614c7b..0932a8aaeb1 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -435,7 +435,7 @@ repos:
entry: ./scripts/ci/pre_commit/replace_bad_characters.py
language: python
types: [file, text]
- exclude:
^clients/gen/go\.sh$|^\.gitmodules$|.*/dist/.*|\.go$|/go\.(mod|sum)$
+ exclude:
^clients/gen/go\.sh$|^\.gitmodules$|^airflow-core/src/airflow/ui/openapi-gen/|.*/dist/.*|\.go$|/go\.(mod|sum)$
additional_dependencies: ['rich>=12.4.4']
- id: lint-dockerfile
name: Lint Dockerfile
diff --git a/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiError.ts
b/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiError.ts
index 6ec39726d3f..36675d288a5 100644
--- a/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiError.ts
+++ b/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiError.ts
@@ -2,20 +2,20 @@ import type { ApiRequestOptions } from './ApiRequestOptions';
import type { ApiResult } from './ApiResult';
export class ApiError extends Error {
- public readonly url: string;
- public readonly status: number;
- public readonly statusText: string;
- public readonly body: unknown;
- public readonly request: ApiRequestOptions;
+ public readonly url: string;
+ public readonly status: number;
+ public readonly statusText: string;
+ public readonly body: unknown;
+ public readonly request: ApiRequestOptions;
- constructor(request: ApiRequestOptions, response: ApiResult, message:
string) {
- super(message);
+ constructor(request: ApiRequestOptions, response: ApiResult, message:
string) {
+ super(message);
- this.name = 'ApiError';
- this.url = response.url;
- this.status = response.status;
- this.statusText = response.statusText;
- this.body = response.body;
- this.request = request;
- }
+ this.name = 'ApiError';
+ this.url = response.url;
+ this.status = response.status;
+ this.statusText = response.statusText;
+ this.body = response.body;
+ this.request = request;
+ }
}
\ No newline at end of file
diff --git
a/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiRequestOptions.ts
b/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiRequestOptions.ts
index 797758dfd3c..939a0aa4c8b 100644
--- a/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiRequestOptions.ts
+++ b/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiRequestOptions.ts
@@ -1,21 +1,21 @@
export type ApiRequestOptions<T = unknown> = {
- readonly body?: any;
- readonly cookies?: Record<string, unknown>;
- readonly errors?: Record<number | string, string>;
- readonly formData?: Record<string, unknown> | any[] | Blob | File;
- readonly headers?: Record<string, unknown>;
- readonly mediaType?: string;
- readonly method:
- | 'DELETE'
- | 'GET'
- | 'HEAD'
- | 'OPTIONS'
- | 'PATCH'
- | 'POST'
- | 'PUT';
- readonly path?: Record<string, unknown>;
- readonly query?: Record<string, unknown>;
- readonly responseHeader?: string;
- readonly responseTransformer?: (data: unknown) => Promise<T>;
- readonly url: string;
+ readonly body?: any;
+ readonly cookies?: Record<string, unknown>;
+ readonly errors?: Record<number | string, string>;
+ readonly formData?: Record<string, unknown> | any[] | Blob | File;
+ readonly headers?: Record<string, unknown>;
+ readonly mediaType?: string;
+ readonly method:
+ | 'DELETE'
+ | 'GET'
+ | 'HEAD'
+ | 'OPTIONS'
+ | 'PATCH'
+ | 'POST'
+ | 'PUT';
+ readonly path?: Record<string, unknown>;
+ readonly query?: Record<string, unknown>;
+ readonly responseHeader?: string;
+ readonly responseTransformer?: (data: unknown) => Promise<T>;
+ readonly url: string;
};
\ No newline at end of file
diff --git a/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiResult.ts
b/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiResult.ts
index ab91f3eb814..4c58e391382 100644
--- a/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiResult.ts
+++ b/airflow-core/src/airflow/ui/openapi-gen/requests/core/ApiResult.ts
@@ -1,7 +1,7 @@
export type ApiResult<TData = any> = {
- readonly body: TData;
- readonly ok: boolean;
- readonly status: number;
- readonly statusText: string;
- readonly url: string;
+ readonly body: TData;
+ readonly ok: boolean;
+ readonly status: number;
+ readonly statusText: string;
+ readonly url: string;
};
\ No newline at end of file
diff --git
a/airflow-core/src/airflow/ui/openapi-gen/requests/core/CancelablePromise.ts
b/airflow-core/src/airflow/ui/openapi-gen/requests/core/CancelablePromise.ts
index b1710dc9b0d..ccc082e8f2a 100644
--- a/airflow-core/src/airflow/ui/openapi-gen/requests/core/CancelablePromise.ts
+++ b/airflow-core/src/airflow/ui/openapi-gen/requests/core/CancelablePromise.ts
@@ -1,126 +1,126 @@
export class CancelError extends Error {
- constructor(message: string) {
- super(message);
- this.name = 'CancelError';
- }
-
- public get isCancelled(): boolean {
- return true;
- }
+ constructor(message: string) {
+ super(message);
+ this.name = 'CancelError';
+ }
+
+ public get isCancelled(): boolean {
+ return true;
+ }
}
export interface OnCancel {
- readonly isResolved: boolean;
- readonly isRejected: boolean;
- readonly isCancelled: boolean;
+ readonly isResolved: boolean;
+ readonly isRejected: boolean;
+ readonly isCancelled: boolean;
- (cancelHandler: () => void): void;
+ (cancelHandler: () => void): void;
}
export class CancelablePromise<T> implements Promise<T> {
- private _isResolved: boolean;
- private _isRejected: boolean;
- private _isCancelled: boolean;
- readonly cancelHandlers: (() => void)[];
- readonly promise: Promise<T>;
- private _resolve?: (value: T | PromiseLike<T>) => void;
- private _reject?: (reason?: unknown) => void;
-
- constructor(
- executor: (
- resolve: (value: T | PromiseLike<T>) => void,
- reject: (reason?: unknown) => void,
- onCancel: OnCancel
- ) => void
- ) {
- this._isResolved = false;
- this._isRejected = false;
- this._isCancelled = false;
- this.cancelHandlers = [];
- this.promise = new Promise<T>((resolve, reject) => {
- this._resolve = resolve;
- this._reject = reject;
-
- const onResolve = (value: T | PromiseLike<T>): void => {
- if (this._isResolved || this._isRejected || this._isCancelled)
{
- return;
- }
- this._isResolved = true;
- if (this._resolve) this._resolve(value);
- };
-
- const onReject = (reason?: unknown): void => {
- if (this._isResolved || this._isRejected || this._isCancelled)
{
- return;
- }
- this._isRejected = true;
- if (this._reject) this._reject(reason);
- };
-
- const onCancel = (cancelHandler: () => void): void => {
- if (this._isResolved || this._isRejected || this._isCancelled)
{
- return;
- }
- this.cancelHandlers.push(cancelHandler);
- };
-
- Object.defineProperty(onCancel, 'isResolved', {
- get: (): boolean => this._isResolved,
- });
-
- Object.defineProperty(onCancel, 'isRejected', {
- get: (): boolean => this._isRejected,
- });
-
- Object.defineProperty(onCancel, 'isCancelled', {
- get: (): boolean => this._isCancelled,
- });
-
- return executor(onResolve, onReject, onCancel as OnCancel);
- });
- }
-
- get [Symbol.toStringTag]() {
- return "Cancellable Promise";
- }
-
- public then<TResult1 = T, TResult2 = never>(
- onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
- onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) |
null
- ): Promise<TResult1 | TResult2> {
- return this.promise.then(onFulfilled, onRejected);
- }
-
- public catch<TResult = never>(
- onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) |
null
- ): Promise<T | TResult> {
- return this.promise.catch(onRejected);
- }
-
- public finally(onFinally?: (() => void) | null): Promise<T> {
- return this.promise.finally(onFinally);
- }
-
- public cancel(): void {
- if (this._isResolved || this._isRejected || this._isCancelled) {
- return;
- }
- this._isCancelled = true;
- if (this.cancelHandlers.length) {
- try {
- for (const cancelHandler of this.cancelHandlers) {
- cancelHandler();
- }
- } catch (error) {
- console.warn('Cancellation threw an error', error);
- return;
- }
- }
- this.cancelHandlers.length = 0;
- if (this._reject) this._reject(new CancelError('Request aborted'));
- }
-
- public get isCancelled(): boolean {
- return this._isCancelled;
- }
+ private _isResolved: boolean;
+ private _isRejected: boolean;
+ private _isCancelled: boolean;
+ readonly cancelHandlers: (() => void)[];
+ readonly promise: Promise<T>;
+ private _resolve?: (value: T | PromiseLike<T>) => void;
+ private _reject?: (reason?: unknown) => void;
+
+ constructor(
+ executor: (
+ resolve: (value: T | PromiseLike<T>) => void,
+ reject: (reason?: unknown) => void,
+ onCancel: OnCancel
+ ) => void
+ ) {
+ this._isResolved = false;
+ this._isRejected = false;
+ this._isCancelled = false;
+ this.cancelHandlers = [];
+ this.promise = new Promise<T>((resolve, reject) => {
+ this._resolve = resolve;
+ this._reject = reject;
+
+ const onResolve = (value: T | PromiseLike<T>): void => {
+ if (this._isResolved || this._isRejected ||
this._isCancelled) {
+ return;
+ }
+ this._isResolved = true;
+ if (this._resolve) this._resolve(value);
+ };
+
+ const onReject = (reason?: unknown): void => {
+ if (this._isResolved || this._isRejected ||
this._isCancelled) {
+ return;
+ }
+ this._isRejected = true;
+ if (this._reject) this._reject(reason);
+ };
+
+ const onCancel = (cancelHandler: () => void): void => {
+ if (this._isResolved || this._isRejected ||
this._isCancelled) {
+ return;
+ }
+ this.cancelHandlers.push(cancelHandler);
+ };
+
+ Object.defineProperty(onCancel, 'isResolved', {
+ get: (): boolean => this._isResolved,
+ });
+
+ Object.defineProperty(onCancel, 'isRejected', {
+ get: (): boolean => this._isRejected,
+ });
+
+ Object.defineProperty(onCancel, 'isCancelled', {
+ get: (): boolean => this._isCancelled,
+ });
+
+ return executor(onResolve, onReject, onCancel as
OnCancel);
+ });
+ }
+
+ get [Symbol.toStringTag]() {
+ return "Cancellable Promise";
+ }
+
+ public then<TResult1 = T, TResult2 = never>(
+ onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>)
| null,
+ onRejected?: ((reason: unknown) => TResult2 |
PromiseLike<TResult2>) | null
+ ): Promise<TResult1 | TResult2> {
+ return this.promise.then(onFulfilled, onRejected);
+ }
+
+ public catch<TResult = never>(
+ onRejected?: ((reason: unknown) => TResult |
PromiseLike<TResult>) | null
+ ): Promise<T | TResult> {
+ return this.promise.catch(onRejected);
+ }
+
+ public finally(onFinally?: (() => void) | null): Promise<T> {
+ return this.promise.finally(onFinally);
+ }
+
+ public cancel(): void {
+ if (this._isResolved || this._isRejected || this._isCancelled) {
+ return;
+ }
+ this._isCancelled = true;
+ if (this.cancelHandlers.length) {
+ try {
+ for (const cancelHandler of
this.cancelHandlers) {
+ cancelHandler();
+ }
+ } catch (error) {
+ console.warn('Cancellation threw an error',
error);
+ return;
+ }
+ }
+ this.cancelHandlers.length = 0;
+ if (this._reject) this._reject(new CancelError('Request
aborted'));
+ }
+
+ public get isCancelled(): boolean {
+ return this._isCancelled;
+ }
}
\ No newline at end of file
diff --git a/airflow-core/src/airflow/ui/openapi-gen/requests/core/OpenAPI.ts
b/airflow-core/src/airflow/ui/openapi-gen/requests/core/OpenAPI.ts
index 491ac0172ba..3631974d81b 100644
--- a/airflow-core/src/airflow/ui/openapi-gen/requests/core/OpenAPI.ts
+++ b/airflow-core/src/airflow/ui/openapi-gen/requests/core/OpenAPI.ts
@@ -25,33 +25,33 @@ export class Interceptors<T> {
}
export type OpenAPIConfig = {
- BASE: string;
- CREDENTIALS: 'include' | 'omit' | 'same-origin';
- ENCODE_PATH?: ((path: string) => string) | undefined;
- HEADERS?: Headers | Resolver<Headers> | undefined;
- PASSWORD?: string | Resolver<string> | undefined;
- TOKEN?: string | Resolver<string> | undefined;
- USERNAME?: string | Resolver<string> | undefined;
- VERSION: string;
- WITH_CREDENTIALS: boolean;
- interceptors: {
- request: Interceptors<AxiosRequestConfig>;
- response: Interceptors<AxiosResponse>;
- };
+ BASE: string;
+ CREDENTIALS: 'include' | 'omit' | 'same-origin';
+ ENCODE_PATH?: ((path: string) => string) | undefined;
+ HEADERS?: Headers | Resolver<Headers> | undefined;
+ PASSWORD?: string | Resolver<string> | undefined;
+ TOKEN?: string | Resolver<string> | undefined;
+ USERNAME?: string | Resolver<string> | undefined;
+ VERSION: string;
+ WITH_CREDENTIALS: boolean;
+ interceptors: {
+ request: Interceptors<AxiosRequestConfig>;
+ response: Interceptors<AxiosResponse>;
+ };
};
export const OpenAPI: OpenAPIConfig = {
- BASE: '',
- CREDENTIALS: 'include',
- ENCODE_PATH: undefined,
- HEADERS: undefined,
- PASSWORD: undefined,
- TOKEN: undefined,
- USERNAME: undefined,
- VERSION: '2',
- WITH_CREDENTIALS: false,
- interceptors: {
- request: new Interceptors(),
- response: new Interceptors(),
- },
+ BASE: '',
+ CREDENTIALS: 'include',
+ ENCODE_PATH: undefined,
+ HEADERS: undefined,
+ PASSWORD: undefined,
+ TOKEN: undefined,
+ USERNAME: undefined,
+ VERSION: '2',
+ WITH_CREDENTIALS: false,
+ interceptors: {
+ request: new Interceptors(),
+ response: new Interceptors(),
+ },
};
\ No newline at end of file
diff --git a/airflow-core/src/airflow/ui/openapi-gen/requests/core/request.ts
b/airflow-core/src/airflow/ui/openapi-gen/requests/core/request.ts
index ebd81169e22..ecc2e393cdc 100644
--- a/airflow-core/src/airflow/ui/openapi-gen/requests/core/request.ts
+++ b/airflow-core/src/airflow/ui/openapi-gen/requests/core/request.ts
@@ -9,292 +9,292 @@ import type { OnCancel } from './CancelablePromise';
import type { OpenAPIConfig } from './OpenAPI';
export const isString = (value: unknown): value is string => {
- return typeof value === 'string';
+ return typeof value === 'string';
};
export const isStringWithValue = (value: unknown): value is string => {
- return isString(value) && value !== '';
+ return isString(value) && value !== '';
};
export const isBlob = (value: any): value is Blob => {
- return value instanceof Blob;
+ return value instanceof Blob;
};
export const isFormData = (value: unknown): value is FormData => {
- return value instanceof FormData;
+ return value instanceof FormData;
};
export const isSuccess = (status: number): boolean => {
- return status >= 200 && status < 300;
+ return status >= 200 && status < 300;
};
export const base64 = (str: string): string => {
- try {
- return btoa(str);
- } catch (err) {
- // @ts-ignore
- return Buffer.from(str).toString('base64');
- }
+ try {
+ return btoa(str);
+ } catch (err) {
+ // @ts-ignore
+ return Buffer.from(str).toString('base64');
+ }
};
export const getQueryString = (params: Record<string, unknown>): string => {
- const qs: string[] = [];
-
- const append = (key: string, value: unknown) => {
-
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
- };
-
- const encodePair = (key: string, value: unknown) => {
- if (value === undefined || value === null) {
- return;
- }
-
- if (value instanceof Date) {
- append(key, value.toISOString());
- } else if (Array.isArray(value)) {
- value.forEach(v => encodePair(key, v));
- } else if (typeof value === 'object') {
- Object.entries(value).forEach(([k, v]) =>
encodePair(`${key}[${k}]`, v));
- } else {
- append(key, value);
- }
- };
-
- Object.entries(params).forEach(([key, value]) => encodePair(key, value));
-
- return qs.length ? `?${qs.join('&')}` : '';
+ const qs: string[] = [];
+
+ const append = (key: string, value: unknown) => {
+
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
+ };
+
+ const encodePair = (key: string, value: unknown) => {
+ if (value === undefined || value === null) {
+ return;
+ }
+
+ if (value instanceof Date) {
+ append(key, value.toISOString());
+ } else if (Array.isArray(value)) {
+ value.forEach(v => encodePair(key, v));
+ } else if (typeof value === 'object') {
+ Object.entries(value).forEach(([k, v]) =>
encodePair(`${key}[${k}]`, v));
+ } else {
+ append(key, value);
+ }
+ };
+
+ Object.entries(params).forEach(([key, value]) => encodePair(key,
value));
+
+ return qs.length ? `?${qs.join('&')}` : '';
};
const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
- const encoder = config.ENCODE_PATH || encodeURI;
-
- const path = options.url
- .replace('{api-version}', config.VERSION)
- .replace(/{(.*?)}/g, (substring: string, group: string) => {
- if (options.path?.hasOwnProperty(group)) {
- return encoder(String(options.path[group]));
- }
- return substring;
- });
-
- const url = config.BASE + path;
- return options.query ? url + getQueryString(options.query) : url;
+ const encoder = config.ENCODE_PATH || encodeURI;
+
+ const path = options.url
+ .replace('{api-version}', config.VERSION)
+ .replace(/{(.*?)}/g, (substring: string, group: string) => {
+ if (options.path?.hasOwnProperty(group)) {
+ return encoder(String(options.path[group]));
+ }
+ return substring;
+ });
+
+ const url = config.BASE + path;
+ return options.query ? url + getQueryString(options.query) : url;
};
export const getFormData = (options: ApiRequestOptions): FormData | undefined
=> {
- if (options.formData) {
- const formData = new FormData();
-
- const process = (key: string, value: unknown) => {
- if (isString(value) || isBlob(value)) {
- formData.append(key, value);
- } else {
- formData.append(key, JSON.stringify(value));
- }
- };
-
- Object.entries(options.formData)
- .filter(([, value]) => value !== undefined && value !== null)
- .forEach(([key, value]) => {
- if (Array.isArray(value)) {
- value.forEach(v => process(key, v));
- } else {
- process(key, value);
- }
- });
-
- return formData;
- }
- return undefined;
+ if (options.formData) {
+ const formData = new FormData();
+
+ const process = (key: string, value: unknown) => {
+ if (isString(value) || isBlob(value)) {
+ formData.append(key, value);
+ } else {
+ formData.append(key, JSON.stringify(value));
+ }
+ };
+
+ Object.entries(options.formData)
+ .filter(([, value]) => value !== undefined && value !==
null)
+ .forEach(([key, value]) => {
+ if (Array.isArray(value)) {
+ value.forEach(v => process(key, v));
+ } else {
+ process(key, value);
+ }
+ });
+
+ return formData;
+ }
+ return undefined;
};
type Resolver<T> = (options: ApiRequestOptions<T>) => Promise<T>;
export const resolve = async <T>(options: ApiRequestOptions<T>, resolver?: T |
Resolver<T>): Promise<T | undefined> => {
- if (typeof resolver === 'function') {
- return (resolver as Resolver<T>)(options);
- }
- return resolver;
+ if (typeof resolver === 'function') {
+ return (resolver as Resolver<T>)(options);
+ }
+ return resolver;
};
export const getHeaders = async <T>(config: OpenAPIConfig, options:
ApiRequestOptions<T>): Promise<Record<string, string>> => {
- const [token, username, password, additionalHeaders] = await Promise.all([
- // @ts-ignore
- resolve(options, config.TOKEN),
- // @ts-ignore
- resolve(options, config.USERNAME),
- // @ts-ignore
- resolve(options, config.PASSWORD),
- // @ts-ignore
- resolve(options, config.HEADERS),
- ]);
-
- const headers = Object.entries({
- Accept: 'application/json',
- ...additionalHeaders,
- ...options.headers,
- })
- .filter(([, value]) => value !== undefined && value !== null)
- .reduce((headers, [key, value]) => ({
- ...headers,
- [key]: String(value),
- }), {} as Record<string, string>);
-
- if (isStringWithValue(token)) {
- headers['Authorization'] = `Bearer ${token}`;
- }
-
- if (isStringWithValue(username) && isStringWithValue(password)) {
- const credentials = base64(`${username}:${password}`);
- headers['Authorization'] = `Basic ${credentials}`;
- }
-
- if (options.body !== undefined) {
- if (options.mediaType) {
- headers['Content-Type'] = options.mediaType;
- } else if (isBlob(options.body)) {
- headers['Content-Type'] = options.body.type ||
'application/octet-stream';
- } else if (isString(options.body)) {
- headers['Content-Type'] = 'text/plain';
- } else if (!isFormData(options.body)) {
- headers['Content-Type'] = 'application/json';
- }
- } else if (options.formData !== undefined) {
- if (options.mediaType) {
- headers['Content-Type'] = options.mediaType;
- }
- }
-
- return headers;
+ const [token, username, password, additionalHeaders] = await
Promise.all([
+ // @ts-ignore
+ resolve(options, config.TOKEN),
+ // @ts-ignore
+ resolve(options, config.USERNAME),
+ // @ts-ignore
+ resolve(options, config.PASSWORD),
+ // @ts-ignore
+ resolve(options, config.HEADERS),
+ ]);
+
+ const headers = Object.entries({
+ Accept: 'application/json',
+ ...additionalHeaders,
+ ...options.headers,
+ })
+ .filter(([, value]) => value !== undefined && value !== null)
+ .reduce((headers, [key, value]) => ({
+ ...headers,
+ [key]: String(value),
+ }), {} as Record<string, string>);
+
+ if (isStringWithValue(token)) {
+ headers['Authorization'] = `Bearer ${token}`;
+ }
+
+ if (isStringWithValue(username) && isStringWithValue(password)) {
+ const credentials = base64(`${username}:${password}`);
+ headers['Authorization'] = `Basic ${credentials}`;
+ }
+
+ if (options.body !== undefined) {
+ if (options.mediaType) {
+ headers['Content-Type'] = options.mediaType;
+ } else if (isBlob(options.body)) {
+ headers['Content-Type'] = options.body.type ||
'application/octet-stream';
+ } else if (isString(options.body)) {
+ headers['Content-Type'] = 'text/plain';
+ } else if (!isFormData(options.body)) {
+ headers['Content-Type'] = 'application/json';
+ }
+ } else if (options.formData !== undefined) {
+ if (options.mediaType) {
+ headers['Content-Type'] = options.mediaType;
+ }
+ }
+
+ return headers;
};
export const getRequestBody = (options: ApiRequestOptions): unknown => {
- if (options.body) {
- return options.body;
- }
- return undefined;
+ if (options.body) {
+ return options.body;
+ }
+ return undefined;
};
export const sendRequest = async <T>(
- config: OpenAPIConfig,
- options: ApiRequestOptions<T>,
- url: string,
- body: unknown,
- formData: FormData | undefined,
- headers: Record<string, string>,
- onCancel: OnCancel,
- axiosClient: AxiosInstance
+ config: OpenAPIConfig,
+ options: ApiRequestOptions<T>,
+ url: string,
+ body: unknown,
+ formData: FormData | undefined,
+ headers: Record<string, string>,
+ onCancel: OnCancel,
+ axiosClient: AxiosInstance
): Promise<AxiosResponse<T>> => {
- const controller = new AbortController();
-
- let requestConfig: AxiosRequestConfig = {
- data: body ?? formData,
- headers,
- method: options.method,
- signal: controller.signal,
- url,
- withCredentials: config.WITH_CREDENTIALS,
- };
-
- onCancel(() => controller.abort());
-
- for (const fn of config.interceptors.request._fns) {
- requestConfig = await fn(requestConfig);
- }
-
- try {
- return await axiosClient.request(requestConfig);
- } catch (error) {
- const axiosError = error as AxiosError<T>;
- if (axiosError.response) {
- return axiosError.response;
- }
- throw error;
- }
+ const controller = new AbortController();
+
+ let requestConfig: AxiosRequestConfig = {
+ data: body ?? formData,
+ headers,
+ method: options.method,
+ signal: controller.signal,
+ url,
+ withCredentials: config.WITH_CREDENTIALS,
+ };
+
+ onCancel(() => controller.abort());
+
+ for (const fn of config.interceptors.request._fns) {
+ requestConfig = await fn(requestConfig);
+ }
+
+ try {
+ return await axiosClient.request(requestConfig);
+ } catch (error) {
+ const axiosError = error as AxiosError<T>;
+ if (axiosError.response) {
+ return axiosError.response;
+ }
+ throw error;
+ }
};
export const getResponseHeader = (response: AxiosResponse<unknown>,
responseHeader?: string): string | undefined => {
- if (responseHeader) {
- const content = response.headers[responseHeader];
- if (isString(content)) {
- return content;
- }
- }
- return undefined;
+ if (responseHeader) {
+ const content = response.headers[responseHeader];
+ if (isString(content)) {
+ return content;
+ }
+ }
+ return undefined;
};
export const getResponseBody = (response: AxiosResponse<unknown>): unknown => {
- if (response.status !== 204) {
- return response.data;
- }
- return undefined;
+ if (response.status !== 204) {
+ return response.data;
+ }
+ return undefined;
};
export const catchErrorCodes = (options: ApiRequestOptions, result:
ApiResult): void => {
- const errors: Record<number, string> = {
- 400: 'Bad Request',
- 401: 'Unauthorized',
- 402: 'Payment Required',
- 403: 'Forbidden',
- 404: 'Not Found',
- 405: 'Method Not Allowed',
- 406: 'Not Acceptable',
- 407: 'Proxy Authentication Required',
- 408: 'Request Timeout',
- 409: 'Conflict',
- 410: 'Gone',
- 411: 'Length Required',
- 412: 'Precondition Failed',
- 413: 'Payload Too Large',
- 414: 'URI Too Long',
- 415: 'Unsupported Media Type',
- 416: 'Range Not Satisfiable',
- 417: 'Expectation Failed',
- 418: 'Im a teapot',
- 421: 'Misdirected Request',
- 422: 'Unprocessable Content',
- 423: 'Locked',
- 424: 'Failed Dependency',
- 425: 'Too Early',
- 426: 'Upgrade Required',
- 428: 'Precondition Required',
- 429: 'Too Many Requests',
- 431: 'Request Header Fields Too Large',
- 451: 'Unavailable For Legal Reasons',
- 500: 'Internal Server Error',
- 501: 'Not Implemented',
- 502: 'Bad Gateway',
- 503: 'Service Unavailable',
- 504: 'Gateway Timeout',
- 505: 'HTTP Version Not Supported',
- 506: 'Variant Also Negotiates',
- 507: 'Insufficient Storage',
- 508: 'Loop Detected',
- 510: 'Not Extended',
- 511: 'Network Authentication Required',
- ...options.errors,
- }
-
- const error = errors[result.status];
- if (error) {
- throw new ApiError(options, result, error);
- }
-
- if (!result.ok) {
- const errorStatus = result.status ?? 'unknown';
- const errorStatusText = result.statusText ?? 'unknown';
- const errorBody = (() => {
- try {
- return JSON.stringify(result.body, null, 2);
- } catch (e) {
- return undefined;
- }
- })();
-
- throw new ApiError(options, result,
- `Generic Error: status: ${errorStatus}; status text:
${errorStatusText}; body: ${errorBody}`
- );
- }
+ const errors: Record<number, string> = {
+ 400: 'Bad Request',
+ 401: 'Unauthorized',
+ 402: 'Payment Required',
+ 403: 'Forbidden',
+ 404: 'Not Found',
+ 405: 'Method Not Allowed',
+ 406: 'Not Acceptable',
+ 407: 'Proxy Authentication Required',
+ 408: 'Request Timeout',
+ 409: 'Conflict',
+ 410: 'Gone',
+ 411: 'Length Required',
+ 412: 'Precondition Failed',
+ 413: 'Payload Too Large',
+ 414: 'URI Too Long',
+ 415: 'Unsupported Media Type',
+ 416: 'Range Not Satisfiable',
+ 417: 'Expectation Failed',
+ 418: 'Im a teapot',
+ 421: 'Misdirected Request',
+ 422: 'Unprocessable Content',
+ 423: 'Locked',
+ 424: 'Failed Dependency',
+ 425: 'Too Early',
+ 426: 'Upgrade Required',
+ 428: 'Precondition Required',
+ 429: 'Too Many Requests',
+ 431: 'Request Header Fields Too Large',
+ 451: 'Unavailable For Legal Reasons',
+ 500: 'Internal Server Error',
+ 501: 'Not Implemented',
+ 502: 'Bad Gateway',
+ 503: 'Service Unavailable',
+ 504: 'Gateway Timeout',
+ 505: 'HTTP Version Not Supported',
+ 506: 'Variant Also Negotiates',
+ 507: 'Insufficient Storage',
+ 508: 'Loop Detected',
+ 510: 'Not Extended',
+ 511: 'Network Authentication Required',
+ ...options.errors,
+ }
+
+ const error = errors[result.status];
+ if (error) {
+ throw new ApiError(options, result, error);
+ }
+
+ if (!result.ok) {
+ const errorStatus = result.status ?? 'unknown';
+ const errorStatusText = result.statusText ?? 'unknown';
+ const errorBody = (() => {
+ try {
+ return JSON.stringify(result.body, null, 2);
+ } catch (e) {
+ return undefined;
+ }
+ })();
+
+ throw new ApiError(options, result,
+ `Generic Error: status: ${errorStatus}; status text:
${errorStatusText}; body: ${errorBody}`
+ );
+ }
};
/**
@@ -306,42 +306,42 @@ export const catchErrorCodes = (options:
ApiRequestOptions, result: ApiResult):
* @throws ApiError
*/
export const request = <T>(config: OpenAPIConfig, options:
ApiRequestOptions<T>, axiosClient: AxiosInstance = axios): CancelablePromise<T>
=> {
- return new CancelablePromise(async (resolve, reject, onCancel) => {
- try {
- const url = getUrl(config, options);
- const formData = getFormData(options);
- const body = getRequestBody(options);
- const headers = await getHeaders(config, options);
-
- if (!onCancel.isCancelled) {
- let response = await sendRequest<T>(config, options, url,
body, formData, headers, onCancel, axiosClient);
-
- for (const fn of config.interceptors.response._fns) {
- response = await fn(response);
- }
-
- const responseBody = getResponseBody(response);
- const responseHeader = getResponseHeader(response,
options.responseHeader);
-
- let transformedBody = responseBody;
- if (options.responseTransformer && isSuccess(response.status))
{
- transformedBody = await
options.responseTransformer(responseBody)
- }
-
- const result: ApiResult = {
- url,
- ok: isSuccess(response.status),
- status: response.status,
- statusText: response.statusText,
- body: responseHeader ?? transformedBody,
- };
-
- catchErrorCodes(options, result);
-
- resolve(result.body);
- }
- } catch (error) {
- reject(error);
- }
- });
+ return new CancelablePromise(async (resolve, reject, onCancel) => {
+ try {
+ const url = getUrl(config, options);
+ const formData = getFormData(options);
+ const body = getRequestBody(options);
+ const headers = await getHeaders(config, options);
+
+ if (!onCancel.isCancelled) {
+ let response = await sendRequest<T>(config,
options, url, body, formData, headers, onCancel, axiosClient);
+
+ for (const fn of
config.interceptors.response._fns) {
+ response = await fn(response);
+ }
+
+ const responseBody = getResponseBody(response);
+ const responseHeader =
getResponseHeader(response, options.responseHeader);
+
+ let transformedBody = responseBody;
+ if (options.responseTransformer &&
isSuccess(response.status)) {
+ transformedBody = await
options.responseTransformer(responseBody)
+ }
+
+ const result: ApiResult = {
+ url,
+ ok: isSuccess(response.status),
+ status: response.status,
+ statusText: response.statusText,
+ body: responseHeader ?? transformedBody,
+ };
+
+ catchErrorCodes(options, result);
+
+ resolve(result.body);
+ }
+ } catch (error) {
+ reject(error);
+ }
+ });
};
\ No newline at end of file