feat: 提供更多可使用的类型

pull/49/head
zjx0905 2023-04-18 11:14:57 +08:00
parent fd07afa0a0
commit 0dc58a4b0c
10 changed files with 112 additions and 46 deletions

View File

@ -118,8 +118,8 @@ function sidebar() {
{ text: '动态地址', link: '/basics/dynamic-url' }, { text: '动态地址', link: '/basics/dynamic-url' },
{ text: '参数系列化', link: '/basics/params-serializer' }, { text: '参数系列化', link: '/basics/params-serializer' },
{ text: '转换数据', link: '/basics/transform-data' }, { text: '转换数据', link: '/basics/transform-data' },
{ text: '上传文件', link: '/basics/upload' },
{ text: '下载文件', link: '/basics/download' }, { text: '下载文件', link: '/basics/download' },
{ text: '上传文件', link: '/basics/upload' },
{ text: '错误处理', link: '/basics/error-handler' }, { text: '错误处理', link: '/basics/error-handler' },
{ text: '取消请求', link: '/basics/cancel' }, { text: '取消请求', link: '/basics/cancel' },
], ],

View File

@ -10,7 +10,6 @@ function main() {
consola.info('Clean'); consola.info('Clean');
const exist = exec('git branch --list docs', { const exist = exec('git branch --list docs', {
stdio: 'pipe', stdio: 'pipe',
encoding: 'utf-8',
}) })
.toString() .toString()
.trim(); .trim();

View File

@ -36,7 +36,6 @@ function checkBranch() {
const releaseBranch = 'main'; const releaseBranch = 'main';
const currentBranch = exec('git branch --show-current', { const currentBranch = exec('git branch --show-current', {
stdio: 'pipe', stdio: 'pipe',
encoding: 'utf-8',
}) })
.toString() .toString()
.trim(); .trim();

View File

@ -1,10 +1,7 @@
import path from 'node:path'; import path from 'node:path';
import { createRequire } from 'node:module'; import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { import { ExecSyncOptions, execSync } from 'node:child_process';
ExecSyncOptionsWithStringEncoding,
execSync,
} from 'node:child_process';
export const __dirname = fileURLToPath(new URL('../', import.meta.url)); export const __dirname = fileURLToPath(new URL('../', import.meta.url));
export const require = createRequire(import.meta.url); export const require = createRequire(import.meta.url);
@ -14,10 +11,12 @@ export const distPath = path.resolve(__dirname, 'dist');
export const resolve = (...paths: string[]) => export const resolve = (...paths: string[]) =>
path.resolve(__dirname, ...paths); path.resolve(__dirname, ...paths);
export const exec = ( export const exec = (command: string, options: ExecSyncOptions = {}) =>
command: string, execSync(command, {
options?: ExecSyncOptionsWithStringEncoding, stdio: 'inherit',
) => execSync(command, { stdio: 'inherit', ...(options ?? {}) }); encoding: 'utf-8',
...options,
});
export const getPkgJSON = () => require(pkgPath); export const getPkgJSON = () => require(pkgPath);

View File

@ -30,15 +30,15 @@ export interface AxiosAdapterResponse extends AnyObject {
/** /**
* *
*/ */
status: number; status?: number;
/** /**
* *
*/ */
statusText: string; statusText?: string;
/** /**
* *
*/ */
headers: AnyObject; headers?: AnyObject;
/** /**
* *
*/ */
@ -49,15 +49,15 @@ export interface AxiosAdapterResponseError extends AnyObject {
/** /**
* *
*/ */
status: number; status?: number;
/** /**
* *
*/ */
statusText: string; statusText?: string;
/** /**
* *
*/ */
headers: AnyObject; headers?: AnyObject;
/** /**
* *
*/ */
@ -117,6 +117,8 @@ export interface AxiosAdapterBaseOptions extends AxiosAdapterRequestConfig {
fail(error: AxiosAdapterResponseError): void; fail(error: AxiosAdapterResponseError): void;
} }
export type AxiosAdapterRequestOptions = AxiosAdapterBaseOptions;
export interface AxiosAdapterUploadOptions export interface AxiosAdapterUploadOptions
extends AxiosAdapterBaseOptions, extends AxiosAdapterBaseOptions,
AxiosRequestFormData { AxiosRequestFormData {
@ -129,7 +131,7 @@ export interface AxiosAdapterDownloadOptions extends AxiosAdapterBaseOptions {
} }
export interface AxiosAdapterRequest { export interface AxiosAdapterRequest {
(config: AxiosAdapterBaseOptions): AxiosAdapterTask; (config: AxiosAdapterRequestOptions): AxiosAdapterTask;
} }
export interface AxiosAdapterUpload { export interface AxiosAdapterUpload {
@ -140,10 +142,19 @@ export interface AxiosAdapterDownload {
(config: AxiosAdapterDownloadOptions): AxiosAdapterTask; (config: AxiosAdapterDownloadOptions): AxiosAdapterTask;
} }
export interface AxiosPlatform { export interface AxiosAdapterPlatform {
/**
*
*/
request: AxiosAdapterRequest; request: AxiosAdapterRequest;
upload: AxiosAdapterUpload; /**
*
*/
download: AxiosAdapterDownload; download: AxiosAdapterDownload;
/**
*
*/
upload: AxiosAdapterUpload;
} }
export type AxiosAdapterTask = export type AxiosAdapterTask =
@ -168,8 +179,8 @@ export function getAdapterDefault() {
if (typeof uni !== undef) { if (typeof uni !== undef) {
return { return {
request: uni.request, request: uni.request,
uploadFile: uni.uploadFile,
downloadFile: uni.downloadFile, downloadFile: uni.downloadFile,
uploadFile: uni.uploadFile,
}; };
} else if (typeof wx !== undef) { } else if (typeof wx !== undef) {
return wx; return wx;
@ -209,7 +220,7 @@ export function getAdapterDefault() {
return createAdapter(platform); return createAdapter(platform);
} }
export function createAdapter(platform: AxiosPlatform) { export function createAdapter(platform: AxiosAdapterPlatform) {
assert(isPlainObject(platform), 'platform 不是一个 object'); assert(isPlainObject(platform), 'platform 不是一个 object');
assert(isFunction(platform.request), 'request 不是一个 function'); assert(isFunction(platform.request), 'request 不是一个 function');
assert(isFunction(platform.upload), 'upload 不是一个 function'); assert(isFunction(platform.upload), 'upload 不是一个 function');
@ -221,10 +232,10 @@ export function createAdapter(platform: AxiosPlatform) {
switch (config.type) { switch (config.type) {
case 'request': case 'request':
return processRequest(platform.request, baseOptions); return processRequest(platform.request, baseOptions);
case 'upload':
return processUpload(platform.upload, baseOptions);
case 'download': case 'download':
return processDownload(platform.download, baseOptions); return processDownload(platform.download, baseOptions);
case 'upload':
return processUpload(platform.upload, baseOptions);
} }
} }
@ -337,7 +348,7 @@ export function createAdapter(platform: AxiosPlatform) {
return adapter; return adapter;
} }
export function isPlatform(value: any): value is AxiosPlatform { export function isPlatform(value: any): value is AxiosAdapterPlatform {
return ( return (
isPlainObject(value) && isPlainObject(value) &&
isFunction(value.request) && isFunction(value.request) &&

View File

@ -180,22 +180,50 @@ export interface AxiosRequestConfig
export interface AxiosResponse< export interface AxiosResponse<
TData extends AxiosResponseData = AxiosResponseData, TData extends AxiosResponseData = AxiosResponseData,
> extends Omit<AxiosAdapterResponse, 'data'> { > extends AnyObject {
/** /**
* *
*/ */
config?: AxiosRequestConfig; status: number;
/** /**
* *
*/ */
request?: AxiosAdapterTask; statusText: string;
/**
*
*/
headers: AnyObject;
/** /**
* *
*/ */
data: TData; data: TData;
/**
*
*/
config: AxiosRequestConfig;
/**
*
*/
request?: AxiosAdapterTask;
} }
export interface AxiosResponseError extends AxiosAdapterResponseError { export interface AxiosResponseError extends AnyObject {
/**
*
*/
status: number;
/**
*
*/
statusText: string;
/**
*
*/
headers: AnyObject;
/**
*
*/
data?: AnyObject;
/** /**
* *
*/ */
@ -203,7 +231,7 @@ export interface AxiosResponseError extends AxiosAdapterResponseError {
/** /**
* *
*/ */
config?: AxiosRequestConfig; config: AxiosRequestConfig;
/** /**
* *
*/ */

View File

@ -1,16 +1,13 @@
import { AxiosAdapterRequestType } from '../adapter'; import { AxiosAdapterRequestType } from '../adapter';
import { AxiosRequestConfig } from './Axios'; import { AxiosRequestConfig } from './Axios';
const postRE = /^POST$/i;
const getRE = /^GET$/i;
export function generateType(config: AxiosRequestConfig) { export function generateType(config: AxiosRequestConfig) {
let requestType: AxiosAdapterRequestType = 'request'; let requestType: AxiosAdapterRequestType = 'request';
if (config.upload && postRE.test(config.method!)) { if (config.download && /^GET/i.test(config.method!)) {
requestType = 'upload';
} else if (config.download && getRE.test(config.method!)) {
requestType = 'download'; requestType = 'download';
} else if (config.upload && /^POST/i.test(config.method!)) {
requestType = 'upload';
} }
return requestType; return requestType;

View File

@ -1,4 +1,4 @@
import { isFunction, isPlainObject } from '../helpers/isTypes'; import { isFunction, isPlainObject, isUndefined } from '../helpers/isTypes';
import { import {
AxiosAdapterRequestConfig, AxiosAdapterRequestConfig,
AxiosAdapterRequestMethod, AxiosAdapterRequestMethod,
@ -76,6 +76,16 @@ export function request(config: AxiosRequestConfig) {
response.config = config; response.config = config;
response.request = adapterTask; response.request = adapterTask;
if (isUndefined(response.status)) {
response.status = 200;
}
if (isUndefined(response.statusText)) {
response.statusText = 'OK';
}
if (isUndefined(response.headers)) {
response.headers = {};
}
if (config.validateStatus?.(response.status) ?? true) { if (config.validateStatus?.(response.status) ?? true) {
resolve(response); resolve(response);
} else { } else {
@ -88,6 +98,17 @@ export function request(config: AxiosRequestConfig) {
responseError.isFail = true; responseError.isFail = true;
responseError.config = config; responseError.config = config;
responseError.request = adapterTask; responseError.request = adapterTask;
if (isUndefined(responseError.status)) {
responseError.status = 400;
}
if (isUndefined(responseError.statusText)) {
responseError.statusText = 'Fail Adapter';
}
if (isUndefined(responseError.headers)) {
responseError.headers = {};
}
catchError('request fail', responseError); catchError('request fail', responseError);
} }

View File

@ -4,17 +4,29 @@ export type {
AxiosRequestConfig, AxiosRequestConfig,
AxiosRequestData, AxiosRequestData,
AxiosRequestFormData, AxiosRequestFormData,
AxiosRequestHeaders,
AxiosRequestMethod,
AxiosResponse, AxiosResponse,
AxiosResponseData, AxiosResponseData,
AxiosResponseError, AxiosResponseError,
AxiosProgressEvent,
AxiosProgressCallback,
} from './core/Axios'; } from './core/Axios';
export type { export type {
AxiosAdapter,
AxiosAdapterRequestConfig, AxiosAdapterRequestConfig,
AxiosAdapterRequestMethod,
AxiosAdapterResponse, AxiosAdapterResponse,
AxiosAdapterResponseData, AxiosAdapterResponseData,
AxiosAdapterResponseError, AxiosAdapterResponseError,
AxiosAdapter, AxiosAdapterPlatform,
AxiosPlatform, AxiosAdapterRequest,
AxiosAdapterRequestOptions,
AxiosAdapterDownload,
AxiosAdapterDownloadOptions,
AxiosAdapterUpload,
AxiosAdapterUploadOptions,
AxiosAdapterTask,
} from './adapter'; } from './adapter';
export type { export type {
AxiosInstanceDefaults, AxiosInstanceDefaults,

View File

@ -1,21 +1,21 @@
import { describe, test, expect, vi } from 'vitest'; import { describe, test, expect, vi } from 'vitest';
import { noop } from 'scripts/test.utils'; import { noop } from 'scripts/test.utils';
import { AxiosPlatform, createAdapter } from '@/adapter'; import { AxiosAdapterPlatform, createAdapter } from '@/adapter';
describe('src/adapter.ts', () => { describe('src/adapter.ts', () => {
test('应该抛出异常', () => { test('应该抛出异常', () => {
expect(() => expect(() =>
createAdapter(undefined as unknown as AxiosPlatform), createAdapter(undefined as unknown as AxiosAdapterPlatform),
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
'"[axios-miniprogram]: platform 不是一个 object"', '"[axios-miniprogram]: platform 不是一个 object"',
); );
expect(() => expect(() =>
createAdapter({} as unknown as AxiosPlatform), createAdapter({} as unknown as AxiosAdapterPlatform),
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
'"[axios-miniprogram]: request 不是一个 function"', '"[axios-miniprogram]: request 不是一个 function"',
); );
expect(() => expect(() =>
createAdapter({ request: vi.fn() } as unknown as AxiosPlatform), createAdapter({ request: vi.fn() } as unknown as AxiosAdapterPlatform),
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
'"[axios-miniprogram]: upload 不是一个 function"', '"[axios-miniprogram]: upload 不是一个 function"',
); );
@ -23,7 +23,7 @@ describe('src/adapter.ts', () => {
createAdapter({ createAdapter({
request: vi.fn(), request: vi.fn(),
upload: vi.fn(), upload: vi.fn(),
} as unknown as AxiosPlatform), } as unknown as AxiosAdapterPlatform),
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
'"[axios-miniprogram]: download 不是一个 function"', '"[axios-miniprogram]: download 不是一个 function"',
); );