react-native-template-mario
Version:
react-native template to target multiple platforms.
92 lines (85 loc) • 2.91 kB
text/typescript
/**
* Created by MeePwn
* https://github.com/maybewaityou
*
* description:
*
*/
import { log, throwException } from 'mario-utilities';
import { ErrorCode } from '@enum/ErrorCode';
import { Method } from '@enum/Method';
import { relationalMapping } from './RelationalMapping';
import { IResponse } from './ResponseTypes';
export { IMeta, IRequest } from './ParamsTypes';
export { IError, IResponse } from './ResponseTypes';
/**
* 准备参数映射
*/
export function paramsPrepare(url: string, params: any, method: string = Method.POST): any {
if (method === Method.GET) {
return getMethodParamsPrepare(url, params);
} else if (method.toLowerCase() === Method.POST) {
return postMethodParamsPrepare(url, params);
}
}
/**
* 接收响应映射
*/
export function responseTranslate(url: string, response: IResponse): IResponse {
const translateMap = relationalMapping[url] || {};
const responseMap = translateMap.responseMap;
if (!responseMap) {
throwException(ErrorCode.RESPONSE_MAP_NOT_EXIST, `== 网络响应字段映射不存在 ===>>>> ${url}`);
}
if (Object.keys(responseMap).length === 0) { return response; }
const result = response.result;
const _result: any = {};
Object.keys(result).forEach((key: string) => {
if (responseMap[key]) {
_result[responseMap[key]] = result[key];
} else {
throwException(ErrorCode.MISSING_ANY_PARAMS, `== 网络响应存在缺失字段 ===>>>> ${key}`);
}
});
return { ...response, result: { ..._result } };
}
/**
* GET 方法参数转换
*/
function getMethodParamsPrepare(url: string, params: any): string {
if (!params) { return url; }
let query = '';
const translateMap = relationalMapping[url] || {};
const paramsMap = translateMap.requestMap;
if (!paramsMap) {
throwException(ErrorCode.REQUEST_MAP_NOT_EXIST, `== 网络请求参数字段映射不存在 ===>>>> ${url}`);
}
Object.keys(paramsMap).forEach((key: string) => {
if (params[paramsMap[key]]) {
query += `${key}=${params[paramsMap[key]]}&`;
} else {
throwException(ErrorCode.MISSING_ANY_PARAMS, `== 网络请求存在参数缺失 ===>>>> ${key}`);
}
});
return `${url}?${query.slice(0, query.length - 1)}`;
}
/**
* POST 方法参数转换
*/
function postMethodParamsPrepare(url: string, params: any): object {
if (!params) { return {}; }
const query: any = {};
const translateMap = relationalMapping[url] || {};
const paramsMap = translateMap.requestMap;
if (!paramsMap) {
throwException(ErrorCode.REQUEST_MAP_NOT_EXIST, `== 网络请求参数字段映射不存在 ===>>>> ${url}`);
}
Object.keys(paramsMap).forEach((key: string) => {
if (params[paramsMap[key]]) {
query[key] = params[paramsMap[key]];
} else {
throwException(ErrorCode.MISSING_ANY_PARAMS, `== 网络请求存在参数缺失 ===>>>> ${key}`);
}
});
return query;
}