return-data
在开发时,会经常遇到模块返回的数据格式不一致,导致各种显示的判断逻辑,例如:if (code === 'success') {...}
,这类判断会暴露模块内部的变量和值,不适合维护。
Features
Installing
Using npm:
npm install return-data
Using yarn:
yarn add return-data
Usage
import ReturnData from "return-data";
const returnData = new ReturnData("success", null, "成功");
returnData.getStatus() === "success";
console.log(returnData.getData());
console.log(returnData.getMsg());
returnData.setMsg("更新成功");
console.log(returnData.getMsg());
返回成功或正确的数据:
import ReturnData from "return-data";
function demo() {
return ReturnData.success({
name: "Tom",
});
}
const returnData = demo();
if (ReturnData.isOk(returnData)) {
const data = returnData.getData();
console.log(data);
}
返回失败的数据:
import ReturnData from "return-data";
function demo() {
return ReturnData.fail();
}
const returnData = demo();
if (ReturnData.isFail(returnData)) {
}
自定义异常类:
import { BaseReturn } from "return-data";
class CustomException extends BaseReturn {
static get NOT_FOUND_USER() {
return new CustomException("NOT_FOUND_USER", null, "未找到用户");
}
static isNotFoundUser(obj: any) {
return BaseReturn.getStatusValue(obj) === "NOT_FOUND_USER";
}
}
API
- ReturnData(status: string, data:any = null, msg?: string);
- static success(data?: any): ReturnData
- static fail(data?: any): ReturnData
- static deny(): ReturnData
- static exception(returnData: IReturnData): ReturnData
- static isOk(obj: any): boolean
- static isFail(obj: any): boolean
- static isDeny(obj: any): boolean
deny():ReturnData
import ReturnData from "return-data";
function demo() {
return ReturnData.deny();
}
const returnData = demo();
if (ReturnData.isDeny(returnData)) {
}
exception(returnData: IReturnData): ReturnData
用于返回自定义的异常错误类
import ReturnData, { BaseReturn } from "return-data";
class CustomException extends BaseReturn {
static get NOT_FOUND_USER() {
return new CustomException("NOT_FOUND_USER", null, "未找到用户");
}
static isNotFoundUser(obj: any) {
return BaseReturn.getStatusValue(obj) === "NOT_FOUND_USER";
}
}
function demo() {
return ReturnData.exception(CustomException.NOT_FOUND_USER);
}
const returnData = demo();
if (CustomException.isNotFoundUser(returnData)) {
}