Skip to content

Commit 70fbe11

Browse files
committed
feat: 增加onBeforeRequest回调函数
1 parent f606409 commit 70fbe11

File tree

8 files changed

+85
-90
lines changed

8 files changed

+85
-90
lines changed

src/adapters/axios.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import type { AxiosRequestConfig, AxiosResponse } from 'axios';
1919
export const axiosAdapter = (
2020
axios: { request: (config: AxiosRequestConfig) => Promise<AxiosResponse> },
2121
returningData: (response: AxiosResponse) => any = (response) => response.data,
22-
): OpenapiClientAdapter => {
22+
): OpenapiClientAdapter<AxiosRequestConfig> => {
2323
return {
2424
async request(opts, utils) {
2525
const body = utils.formatBody(opts.requestBodyType, opts.body);
@@ -29,8 +29,7 @@ export const axiosAdapter = (
2929
: typeof opts.credentials === 'string' || opts.credentials === true
3030
? true
3131
: undefined;
32-
33-
const result = await axios.request({
32+
const config: AxiosRequestConfig = {
3433
url: opts.uri,
3534
method: opts.method,
3635
params: opts.query,
@@ -39,7 +38,9 @@ export const axiosAdapter = (
3938
timeout: opts.timeout,
4039
withCredentials: credentials,
4140
responseType: opts.responseType,
42-
});
41+
};
42+
43+
const result = await axios.request(opts.onBeforeRequest?.(config) || config);
4344

4445
return returningData(result);
4546
},

src/adapters/fetch.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ export const fetchAdapter = (opts: {
2323
* fetch的默认参数,每次请求前都会合并对象
2424
*/
2525
fetchOptions?: RequestInit;
26-
}): OpenapiClientAdapter => {
26+
}): OpenapiClientAdapter<RequestInit> => {
2727
const { fetch: fetcher = fetch, baseURL, fetchOptions = {} } = opts;
2828

2929
return {
@@ -36,8 +36,7 @@ export const fetchAdapter = (opts: {
3636
: opts.credentials === true
3737
? 'same-origin'
3838
: 'omit';
39-
40-
const response = await fetcher(url, {
39+
const config: RequestInit = {
4140
...fetchOptions,
4241
method: opts.method,
4342
body,
@@ -46,7 +45,9 @@ export const fetchAdapter = (opts: {
4645
...opts.headers,
4746
},
4847
credentials,
49-
});
48+
};
49+
50+
const response = await fetcher(url, opts.onBeforeRequest?.(config) || config);
5051

5152
return opts.responseType === 'json' ? response.json() : response.text();
5253
},

src/adapters/taro.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,12 @@ export const taroAdapter = (opts: {
3636
/**
3737
* 返回最终数据。默认值:`(res) => res.data`
3838
*/
39-
returningData?: (response: Taro.request.SuccessCallbackResult) => any;
39+
returningData?: (result: Taro.request.SuccessCallbackResult) => any;
4040
/**
4141
* Taro.request()的默认参数,每次请求前都会合并对象
4242
*/
4343
requestOptions?: Taro.request.Option;
44-
}): OpenapiClientAdapter => {
44+
}): OpenapiClientAdapter<Taro.request.Option> => {
4545
const {
4646
returningData = (result) => result.data,
4747
getStatusCode = (result) => result.statusCode,
@@ -62,8 +62,7 @@ export const taroAdapter = (opts: {
6262
: opts.credentials === true
6363
? 'same-origin'
6464
: 'omit';
65-
66-
const result = await request({
65+
const config: Taro.request.Option = {
6766
...requestOptions,
6867
url: baseURL + utils.uriConcatQuery(opts.uri, opts.query),
6968
method: opts.method.toUpperCase() as `${Uppercase<Methods>}`,
@@ -72,7 +71,8 @@ export const taroAdapter = (opts: {
7271
timeout: opts.timeout,
7372
credentials,
7473
responseType: opts.responseType === 'text' ? 'text' : undefined,
75-
});
74+
};
75+
const result = await request(opts.onBeforeRequest?.(config) || config);
7676

7777
const statusCode = getStatusCode(result);
7878
if (statusCode >= 400) {

src/adapters/uniapp.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export const uniappAdapter = (opts: {
4040
* uni.request()的默认参数,每次请求前都会合并对象
4141
*/
4242
requestOptions?: UniApp.RequestOptions;
43-
}): OpenapiClientAdapter => {
43+
}): OpenapiClientAdapter<UniApp.RequestOptions> => {
4444
const {
4545
returningData = (result) => result.data,
4646
getStatusCode = (result) => result.statusCode,
@@ -61,8 +61,7 @@ export const uniappAdapter = (opts: {
6161
: typeof opts.credentials === 'string' || opts.credentials === true
6262
? true
6363
: undefined;
64-
65-
const result = await request({
64+
const config: UniApp.RequestOptions = {
6665
...requestOptions,
6766
url: baseURL + utils.uriConcatQuery(opts.uri, opts.query),
6867
method: opts.method.toUpperCase() as any,
@@ -72,7 +71,8 @@ export const uniappAdapter = (opts: {
7271
withCredentials: credentials,
7372
dataType: opts.responseType === 'json' ? 'json' : undefined,
7473
responseType: opts.responseType === 'text' ? 'text' : undefined,
75-
});
74+
};
75+
const result = await request(opts.onBeforeRequest?.(config) || config);
7676

7777
const statusCode = getStatusCode(result);
7878
if (statusCode >= 400) {

src/base-openapi-client.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { OpenapiClientAdapter, Methods } from './lib/adapter';
22
import { utils } from './utils';
33

44
export namespace BaseOpenapiClient {
5-
export interface UserInputOpts {
5+
export interface UserInputOpts<T extends object = object> {
66
headers?: Record<string, unknown>;
77
/**
88
* 超时时间。单位:`ms`
@@ -20,9 +20,13 @@ export namespace BaseOpenapiClient {
2020
* 响应类型
2121
*/
2222
responseType?: 'json' | 'text';
23+
/**
24+
* 请求之前动态修改配置
25+
*/
26+
onBeforeRequest?: (options: T) => T | void;
2327
}
2428

25-
export interface FullOpts extends UserInputOpts {
29+
export interface FullOpts<T extends object = object> extends UserInputOpts<T> {
2630
params?: Record<string, any>;
2731
query?: Record<string, any>;
2832
body?: Record<string, any> | FormData;
@@ -33,8 +37,8 @@ export namespace BaseOpenapiClient {
3337
} & {};
3438
}
3539

36-
export abstract class BaseOpenapiClient {
37-
constructor(private readonly adapter: OpenapiClientAdapter) {}
40+
export abstract class BaseOpenapiClient<T extends object = object> {
41+
constructor(private readonly adapter: OpenapiClientAdapter<T>) {}
3842

3943
protected replaceURI(uri: string, params?: Record<string, any>) {
4044
if (!params) return uri;
@@ -44,7 +48,11 @@ export abstract class BaseOpenapiClient {
4448
return uri;
4549
}
4650

47-
protected request(uri: string, method: Methods, opts: BaseOpenapiClient.FullOpts = {}) {
51+
protected request(
52+
uri: string,
53+
method: Methods,
54+
opts: BaseOpenapiClient.FullOpts<T> = {},
55+
) {
4856
const contentTypes = this.getContentTypes(uri, method);
4957
const requestBodyType = opts.requestBodyType || contentTypes[0] || 'application/json';
5058
const responseType = opts.responseType || contentTypes[1] || 'json';

src/lib/adapter.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ export const methods = <const>['get', 'post', 'put', 'patch', 'delete'];
44

55
export type Methods = (typeof methods)[number];
66

7-
export interface OpenapiClientAdapter {
7+
export interface OpenapiClientAdapter<T extends object = object> {
88
request(
99
opts: {
1010
/**
@@ -47,6 +47,10 @@ export interface OpenapiClientAdapter {
4747
* 请求报文
4848
*/
4949
headers: Record<string, any>;
50+
/**
51+
* 请求之前动态修改配置
52+
*/
53+
onBeforeRequest?: (options: T) => T | void;
5054
},
5155
helper: typeof utils,
5256
): Promise<any>;

src/lib/generate-template.ts

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ export const generateTemplate = async (
3434

3535
return {
3636
[className]: {
37-
dts: await prettier.format(dts, { parser: 'typescript' }),
38-
js: await prettier.format(js, { parser: 'typescript' }),
37+
dts: await prettier.format(dts, { parser: 'typescript', printWidth: 120 }),
38+
js: await prettier.format(js, { parser: 'typescript', printWidth: 120 }),
3939
},
4040
};
4141
};
@@ -77,7 +77,7 @@ declare namespace ${className} {
7777
export const generateMethodModeClass = (className: string, metas: Metas) => {
7878
return {
7979
dts: `
80-
declare class ${className} extends BaseOpenapiClient {
80+
declare class ${className}<T extends object = object> extends BaseOpenapiClient<T> {
8181
${methods
8282
.map((method) => {
8383
if (!metas[method].length) return '';
@@ -90,12 +90,13 @@ declare class ${className} extends BaseOpenapiClient {
9090
.map((meta) => meta.uri);
9191
9292
let opts: string;
93+
const optType = `${className}_${method}_paths[K]['request'] & BaseOpenapiClient.UserInputOpts<T>`;
9394
if (optionalUris.length === uris.length) {
94-
opts = `[opts?: ${className}_${method}_paths[K]['request']]`;
95+
opts = `[opts?: ${optType}]`;
9596
} else if (optionalUris.length === 0) {
96-
opts = `[opts: ${className}_${method}_paths[K]['request']]`;
97+
opts = `[opts: ${optType}]`;
9798
} else {
98-
opts = `K extends '${optionalUris.join(' | ')}' ? [opts?: ${className}_${method}_paths[K]['request']] : [opts: ${className}_${method}_paths[K]['request']]`;
99+
opts = `K extends '${optionalUris.join(' | ')}' ? [opts?: ${optType}] : [opts: ${optType}]`;
99100
}
100101
101102
return `${method}<K extends keyof ${className}_${method}_paths>(
@@ -130,7 +131,7 @@ var ${className} = class extends BaseOpenapiClient {
130131
export const generateUriModelClass = (className: string, metas: Metas) => {
131132
return {
132133
dts: `
133-
declare class ${className} extends BaseOpenapiClient {
134+
declare class ${className}<T extends object = object> extends BaseOpenapiClient<T> {
134135
${methods
135136
.flatMap((method) => {
136137
return metas[method].map((meta) => {
@@ -139,7 +140,7 @@ declare class ${className} extends BaseOpenapiClient {
139140
140141
return `
141142
${generateComments(meta)}
142-
${camelCase(meta.key)}(opts${optional ? '?' : ''}: ${className}_${method}_paths['${meta.uri}']['request']): Promise<${className}_${method}_paths['${meta.uri}']['response']>`;
143+
${camelCase(meta.key)}(opts${optional ? '?' : ''}: ${className}_${method}_paths['${meta.uri}']['request'] & BaseOpenapiClient.UserInputOpts<T>): Promise<${className}_${method}_paths['${meta.uri}']['response']>`;
143144
});
144145
})
145146
.join('\n')}
@@ -178,7 +179,7 @@ export const generateUriModelClassWithNamespace = (className: string, metas: Met
178179

179180
return {
180181
dts: `
181-
declare class ${className} extends BaseOpenapiClient {
182+
declare class ${className}<T extends object = object> extends BaseOpenapiClient<T> {
182183
${namespaces
183184
.map((ns) => {
184185
return `readonly ${snakeCase(ns)}: {
@@ -192,7 +193,7 @@ declare class ${className} extends BaseOpenapiClient {
192193
193194
return `
194195
${generateComments(meta)}
195-
${camelCase(meta.key)}(opts${optional ? '?' : ''}: ${className}_${method}_paths['${meta.uri}']['request']): Promise<${className}_${method}_paths['${meta.uri}']['response']>`;
196+
${camelCase(meta.key)}(opts${optional ? '?' : ''}: ${className}_${method}_paths['${meta.uri}']['request'] & BaseOpenapiClient.UserInputOpts<T>): Promise<${className}_${method}_paths['${meta.uri}']['response']>`;
196197
});
197198
})
198199
.join('\n')}
@@ -277,7 +278,7 @@ interface ${className}_${method}_paths {
277278
${meta.query.types.length ? `query${meta.query.optional ? '?' : ''}: ${className}.${upperFirst(camelCase(meta.key + '_query'))};` : 'query?: object;'}
278279
${meta.params.types.length ? `params${meta.params.optional ? '?' : ''}: ${className}.${upperFirst(camelCase(meta.key + '_params'))};` : ''}
279280
${meta.body.types.length ? `body${meta.body.optional ? '?' : ''}: ${className}.${upperFirst(camelCase(meta.key + '_body'))};` : ''}
280-
} & BaseOpenapiClient.UserInputOpts;
281+
};
281282
response: ${meta.response.types.length ? `${className}.${upperFirst(camelCase(meta.key + '_response'))}` : 'unknown'}
282283
}>`;
283284
})

0 commit comments

Comments
 (0)