Skip to content

Commit

Permalink
Replace axios entirely for global fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
dqbd committed Mar 5, 2023
1 parent d8991bd commit ba505ce
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 22 deletions.
6 changes: 2 additions & 4 deletions sdk-template-overrides/typescript-axios/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

{{^withSeparateModelsAndApi}}
import type { Configuration } from './configuration';
import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
import globalAxios from 'axios';
{{#withNodeImports}}
// URLSearchParams not necessarily used
// @ts-ignore
Expand All @@ -16,8 +14,8 @@ import FormData from 'form-data'
{{/withNodeImports}}
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common';
import type { RequestArgs } from './base';
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction, createStreamFunction } from './common';
import type { RequestArgs, AxiosRequestConfig, AxiosPromise } from './base';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base';

Expand Down
15 changes: 8 additions & 7 deletions sdk-template-overrides/typescript-axios/apiInner.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
/* eslint-disable */
{{>licenseInfo}}

import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
import { Configuration } from '{{apiRelativeToRoot}}configuration';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '{{apiRelativeToRoot}}common';
// @ts-ignore
import { AxiosPromise, AxiosRequestConfig } from '{{apiRelativeToRoot}}base';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from '{{apiRelativeToRoot}}base';
{{#imports}}
// @ts-ignore
Expand Down Expand Up @@ -223,9 +224,9 @@ export const {{classname}}Fp = function(configuration?: Configuration) {
* @deprecated{{/isDeprecated}}
* @throws {RequiredError}
*/
async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{{{returnType}}}{{^returnType}}void{{/returnType}}>> {
async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: AxiosRequestConfig): Promise<(basePath?: string) => AxiosPromise<{{{returnType}}}{{^returnType}}void{{/returnType}}>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
return createRequestFunction(localVarAxiosArgs, BASE_PATH, configuration);
},
{{/operation}}
}
Expand All @@ -236,7 +237,7 @@ export const {{classname}}Fp = function(configuration?: Configuration) {
* {{&description}}{{/description}}
* @export
*/
export const {{classname}}Factory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
export const {{classname}}Factory = function (configuration?: Configuration, basePath?: string) {
const localVarFp = {{classname}}Fp(configuration)
return {
{{#operation}}
Expand All @@ -253,7 +254,7 @@ export const {{classname}}Factory = function (configuration?: Configuration, bas
* @throws {RequiredError}
*/
{{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: any): AxiosPromise<{{{returnType}}}{{^returnType}}void{{/returnType}}> {
return localVarFp.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options).then((request) => request(axios, basePath));
return localVarFp.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options).then((request) => request(basePath));
},
{{/operation}}
};
Expand Down Expand Up @@ -348,12 +349,12 @@ export class {{classname}} extends BaseAPI {
*/
{{#useSingleRequestParameter}}
public {{nickname}}({{#allParams.0}}requestParameters: {{classname}}{{operationIdCamelCase}}Request{{^hasRequiredParams}} = {}{{/hasRequiredParams}}, {{/allParams.0}}options?: AxiosRequestConfig) {
return {{classname}}Fp(this.configuration).{{nickname}}({{#allParams.0}}{{#allParams}}requestParameters.{{paramName}}, {{/allParams}}{{/allParams.0}}options).then((request) => request(this.axios, this.basePath));
return {{classname}}Fp(this.configuration).{{nickname}}({{#allParams.0}}{{#allParams}}requestParameters.{{paramName}}, {{/allParams}}{{/allParams.0}}options).then((request) => request(this.basePath));
}
{{/useSingleRequestParameter}}
{{^useSingleRequestParameter}}
public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: AxiosRequestConfig) {
return {{classname}}Fp(this.configuration).{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options).then((request) => request(this.axios, this.basePath));
return {{classname}}Fp(this.configuration).{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options).then((request) => request(this.basePath));
}
{{/useSingleRequestParameter}}
{{^-last}}
Expand Down
54 changes: 50 additions & 4 deletions sdk-template-overrides/typescript-axios/baseApi.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,55 @@

import type { Configuration } from './configuration';
// Some imports not used depending on template conditions
// @ts-ignore
import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
import globalAxios from 'axios';

type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'purge' | 'PURGE'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK';

type AxiosHeaderValue = string | string[] | number | boolean | null;

interface RawAxiosHeaders {
[key: string]: AxiosHeaderValue;
}

type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent' | 'Content-Encoding' | 'Authorization';

type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';

type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & {
[Key in CommonRequestHeadersList]: AxiosHeaderValue;
} & {
'Content-Type': ContentType
}>

interface AxiosBasicCredentials {
username: string;
password: string;
}

export interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
auth?: AxiosBasicCredentials;
headers?: RawAxiosRequestHeaders;
data?: D;
}

export interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
}

export type AxiosPromise<T = any> = Promise<AxiosResponse<T>>;

export const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, "");

Expand Down Expand Up @@ -39,7 +85,7 @@ export interface RequestArgs {
export class BaseAPI {
protected configuration: Configuration | undefined;
constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) {
constructor(configuration?: Configuration, protected basePath: string = BASE_PATH) {
if (configuration) {
this.configuration = configuration;
this.basePath = configuration.basePath || this.basePath;
Expand Down
70 changes: 63 additions & 7 deletions sdk-template-overrides/typescript-axios/common.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
{{>licenseInfo}}

import type { Configuration } from "./configuration";
import type { RequestArgs } from "./base";
import type { AxiosInstance, AxiosResponse } from 'axios';
import type { RequestArgs, AxiosResponse } from "./base";
import { RequiredError } from "./base";
{{#withNodeImports}}
import { URL, URLSearchParams } from 'url';
Expand Down Expand Up @@ -134,9 +133,66 @@ export const toPathString = function (url: URL) {
*
* @export
*/
export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) {
return <T = unknown, R = AxiosResponse<T>>(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => {
const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || basePath) + axiosArgs.url};
return axios.request<T, R>(axiosRequestArgs);
export const createStreamFunction = function (
axiosArgs: RequestArgs,
BASE_PATH: string,
configuration?: Configuration
) {
return async (basePath: string = BASE_PATH): Promise<AxiosResponse<ReadableStream>> => {
const axiosRequestArgs = {
...axiosArgs.options,
url: (configuration?.basePath || basePath) + axiosArgs.url,
};
}

const res = await fetch(axiosRequestArgs.url, {
method: axiosRequestArgs.method,
headers: axiosRequestArgs.headers as Record<string, string>,
body: axiosRequestArgs.data,
});

if (!res.ok) {
throw new Error(`Failed to fetch ${res.status}`);
}

return {
data: res.body as ReadableStream,
status: res.status,
statusText: res.statusText,
};
};
};

/**
*
* @export
*/
export const createRequestFunction = function (
axiosArgs: RequestArgs,
BASE_PATH: string,
configuration?: Configuration
) {
return async <T = unknown>(
basePath: string = BASE_PATH
): Promise<AxiosResponse<T>> => {
const axiosRequestArgs = {
...axiosArgs.options,
url: (configuration?.basePath || basePath) + axiosArgs.url,
};

const res = await fetch(axiosRequestArgs.url, {
method: axiosRequestArgs.method,
headers: axiosRequestArgs.headers as Record<string, string>,
body: axiosRequestArgs.data,
});

if (!res.ok) {
throw new Error(`Failed to fetch ${res.status}`);
}

return {
data: (await res.json()) as T,
status: res.status,
statusText: res.statusText,
};
};
};

0 comments on commit ba505ce

Please sign in to comment.