Skip to content

Commit

Permalink
[refactor] 去除返回时的接口限制
Browse files Browse the repository at this point in the history
  • Loading branch information
ThatCoders committed Jul 22, 2024
1 parent d5685b5 commit 373f6ca
Show file tree
Hide file tree
Showing 11 changed files with 111 additions and 57 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@thatcompany/axios",
"version": "1.1.0",
"version": "1.1.1",
"description": "像Spring一样编写前端请求。Like edit Spring Controller, edit TypeScript class for Axios",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
13 changes: 8 additions & 5 deletions src/__test__/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import orderMapper from './repository/OrderMapper';
import { axiosEnhancer } from '../config';
import shopMapper from './repository/ShopMapper';
import userMapper from './repository/UserMapper';

class Test {
async main() {
axiosEnhancer.logger.info('OrderMapper test');
console.table(await orderMapper.getOrderByPayNo('114514'));
axiosEnhancer.logger.info('ShopMapper test');
console.table(await shopMapper.findAll({ thesisPrice: 58 }));
console.table(await shopMapper.findById(1));
// axiosEnhancer.logger.info('OrderMapper test');
// console.table(await orderMapper.getOrderByPayNo('114514'));
// axiosEnhancer.logger.info('ShopMapper test');
// console.table(await shopMapper.findAll({ thesisPrice: 58 }));
// console.table(await shopMapper.findById(1));
axiosEnhancer.logger.info('UserMapper test');
console.table(await userMapper.login());
}
}

Expand Down
11 changes: 11 additions & 0 deletions src/__test__/repository/UserMapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { PostMapping, RequestLog, RequestMapping, RequestSecurityPermit } from '../../decorator';

@RequestMapping('https://auto.thatapi.cn/welcome')
class UserMapper {
@PostMapping('/login')
@RequestLog
@RequestSecurityPermit
async login(userName: string = 'test', password: string = '123456', rememberMe: boolean = false) {}
}

export default new UserMapper();
20 changes: 20 additions & 0 deletions src/data/DATA_RESPONSE_STATUS.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// 状态码枚举
export enum DATA_RESPONSE_STATUS {
OK = 200,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
FORBIDDEN = 403,
NOT_FOUND = 404,
ERROR = 500,
}
// 状态码与消息的映射,直接在 enum 中定义
export namespace DATA_RESPONSE_STATUS_MESSAGES {
export const messages: { [key in DATA_RESPONSE_STATUS]: string } = {
[DATA_RESPONSE_STATUS.OK]: '操作成功',
[DATA_RESPONSE_STATUS.BAD_REQUEST]: '参数错误',
[DATA_RESPONSE_STATUS.UNAUTHORIZED]: '鉴权失败',
[DATA_RESPONSE_STATUS.FORBIDDEN]: '越权操作',
[DATA_RESPONSE_STATUS.NOT_FOUND]: '寻址失败',
[DATA_RESPONSE_STATUS.ERROR]: '系统错误',
};
}
1 change: 1 addition & 0 deletions src/data/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './DATA_META_KEY';
export * from './DATA_LOG_LEVEL';
export * from './DATA_RESPONSE_STATUS';
20 changes: 9 additions & 11 deletions src/decorator/MappingDecorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,13 @@ function BuildMappingDecorator(
if (args.length === 1 && typeof args[0] === 'object') {
args = args[0];
}
if (method === 'POST' || method === 'PUT') {
if (
requestHeaders.hasOwnProperty('Content-Type') &&
requestHeaders['Content-Type'] === 'multipart/form-data'
) {
data = new FormData();
data.append('file', args);
} else {
data = args;
}
// // 处理文件上传
if (
requestHeaders.hasOwnProperty('Content-Type') &&
requestHeaders['Content-Type'] === 'multipart/form-data'
) {
data = new FormData();
data.append('file', args);
} else {
data = {
...param.defaultParams,
Expand Down Expand Up @@ -79,7 +76,8 @@ function BuildMappingDecorator(
method,
safety,
url: target.base + newPath,
[method === 'GET' || method === 'DELETE' ? 'params' : 'data']: data,
data,
params: data,
headers: requestHeaders,
responseType,
queue: RequestQueue,
Expand Down
53 changes: 25 additions & 28 deletions src/requestor/ThatAxios.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import axios, { AxiosResponse } from 'axios';
import { ResponseBody, ResponseStatus, TAxiosRequestConfig, ThatAxiosResponse } from '../type';
import { TAxiosRequestConfig, ThatAxiosResponse, ThatStatus } from '../type';
import { RequestQueue, RequestSecurity } from '../decorator/AxiosDecorator';
import { axiosEnhancer } from '../config';
import { INotifyService } from '../service';
import { DATA_RESPONSE_STATUS } from '../data';

const notifyService: INotifyService = axiosEnhancer.notify;
/**
Expand Down Expand Up @@ -66,50 +67,46 @@ export default class ThatAxios {
public async request(axiosConfig: TAxiosRequestConfig): Promise<ThatAxiosResponse> {
axiosEnhancer.logger.start(axiosConfig);

let RESULT = false;
let STATUS: ThatStatus = new ThatStatus(DATA_RESPONSE_STATUS.OK);

let BODY: ResponseBody = { msg: '', result: false, code: 500 };
let DATA: any = {};

BODY = await this.myAxios(axiosConfig, {
DATA = await this.myAxios(axiosConfig, {
repeat_request_cancel: axiosConfig.queue || false,
})
.then((res: AxiosResponse) => {
if (axiosEnhancer.filer.isBlob(axiosConfig, res)) {
const blob = new Blob([res.data]);
const filename =
decodeURIComponent(decodeURIComponent(res.headers['download-filename'])) || '未闻文件名';
BODY.msg = `下载成功 文件名:${filename}`.trim();
BODY.result = true;
BODY.code = 200;
RESULT = true;
DATA.msg = `下载成功 文件名:${filename}`.trim();
STATUS = new ThatStatus(DATA_RESPONSE_STATUS.OK);
axiosEnhancer.filer.enable && axiosEnhancer.filer.saveBlob(blob, filename);
axiosEnhancer.filer.enable || (BODY.data = blob);
return BODY;
axiosEnhancer.filer.enable || (DATA.data = blob);
return DATA;
}
RESULT = res?.data?.code === 200;
if (RESULT || (!RESULT && res?.data?.status === ResponseStatus.UNAUTHORIZED)) {
return res.data;
}
BODY.msg = '服务器无响应体';
return BODY;
STATUS = new ThatStatus(res.status);
DATA = res?.data;
return DATA;
})
.catch((error) => {
BODY.msg = error.response.data.message;
return BODY;
DATA.msg = error.response.data.message;
return DATA;
});
if (RESULT) {
BODY.result = true;
if (BODY?.rows?.length === 0) {
if (STATUS.code === DATA_RESPONSE_STATUS.OK) {
if (DATA?.rows?.length === 0 || DATA?.length === 0 || DATA?.total === 0) {
notifyService.warn('相关条件未查询到数据');
return { RESULT, BODY };
return { STATUS, DATA };
}
notifyService.success(BODY.msg);
} else if (!RESULT && BODY?.code === ResponseStatus.UNAUTHORIZED) {
notifyService.warn(BODY.msg);
notifyService.success(DATA?.msg || DATA?.message || '请求成功');
} else {
notifyService.error(BODY.msg);
if (STATUS.code === DATA_RESPONSE_STATUS.UNAUTHORIZED) {
notifyService.warn(DATA?.msg || DATA?.message || STATUS.message || '请求失败,请检查登录状态');
} else {
notifyService.error(DATA?.msg || DATA?.message || STATUS.message || '请求失败,请稍后再试');
}
}
axiosEnhancer.logger.end(axiosConfig, { RESULT, BODY });
return { RESULT, BODY };
axiosEnhancer.logger.end(axiosConfig, { STATUS, DATA });
return { STATUS, DATA };
}
}
2 changes: 1 addition & 1 deletion src/service/impl/LogService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export default class LogService implements ILogService {
return;
}
this.info('响应数据源');
this.table(response.BODY);
this.table(response.DATA);
// @ts-ignore
this.trace(axiosConfig.requestLog.func + ' 堆栈');
// this.profile(axiosConfig.requestLog.func + ' 性能', true);
Expand Down
33 changes: 22 additions & 11 deletions src/type/ResponseBody.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { DATA_RESPONSE_STATUS, DATA_RESPONSE_STATUS_MESSAGES } from '../data';

interface ResponseBody<R = any> {
code: number;
code: ThatStatus;
result: boolean;
msg: string;
rows?: R;
Expand All @@ -8,17 +10,26 @@ interface ResponseBody<R = any> {
}

interface ThatAxiosResponse<R = any> {
RESULT: boolean;
BODY: ResponseBody<R>;
DATA: R;
STATUS: ThatStatus;
}

enum ResponseStatus {
OK = 200,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
FORBIDDEN = 403,
NOT_FOUND = 404,
ERROR = 500,
class ThatStatus {
private readonly _code: DATA_RESPONSE_STATUS;

constructor(code: DATA_RESPONSE_STATUS = DATA_RESPONSE_STATUS.OK) {
this._code = code;
}

// 使用映射对象获取消息
get message(): string {
return DATA_RESPONSE_STATUS_MESSAGES.messages[this._code] || 'Unknown Error';
}

// 允许获取状态码
get code(): DATA_RESPONSE_STATUS {
return this._code;
}
}

export { ResponseBody, ThatAxiosResponse, ResponseStatus };
export { ResponseBody, ThatAxiosResponse, DATA_RESPONSE_STATUS_MESSAGES, ThatStatus };
12 changes: 12 additions & 0 deletions src/util/DataUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// TODO: 实现安全的获取json值
function safeGetJsonValue(json: any, keys: string[]): any {
let value = json;
for (const key of keys) {
if (value && typeof value === 'object' && key in value) {
value = value[key];
} else {
return undefined;
}
}
return value;
}
1 change: 1 addition & 0 deletions tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"no-shadowed-variable": false,
"no-unused-expression": false,
"no-empty-interface": false,
"no-namespace": false,
"ban-types": [
false,
[
Expand Down

0 comments on commit 373f6ca

Please sign in to comment.