query-string#stringifyUrl TypeScript Examples
The following examples show how to use
query-string#stringifyUrl.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: fetch.ts From yugong with MIT License | 4 votes |
fetchApi = async (
url: string,
{
method,
headers = {},
body,
mode = 'cors',
credentials,
...others
}: { [keys: string]: any },
dataMap: Api['dataMap']
) => {
// 处理Url
let urlData = url;
let bodyData = { ...body };
if (method === 'GET') {
urlData = stringifyUrl({ url, query: body });
}
if (headers['Content-Type'] === 'application/json') {
bodyData = JSON.stringify(bodyData);
}
// fetch参数
const args: AnyObjectType = {
method,
headers: headers,
};
if (method !== 'GET') {
args.body = bodyData;
}
if (mode) {
args.mode = mode;
}
if (credentials) {
args.credentials = credentials;
}
const res = await fetch(urlData, { ...others, ...args });
/**
* 状态范围
*/
if (res.status >= 200 && res.status < 300) {
const textData = await res.text();
const resultData = JSON.parse(textData);
const body = {
response: resultData,
};
// 结果处理
// 结果到映射
if (dataMap?.length) {
dataMap.forEach(({ source, target, map }) => {
if (!source || !map || !target) {
return;
}
// 从返回数据中获取源数据
const sourceData = lodash.get(body, source);
// 源数据与目标数据的映射关系, 这里不通过getArgumentsItem获取,而是手动获取,这样避免规则标签被过滤
const argMap = map.data; //getArgumentsItem(map, sourceData) as AnyObjectType;
// 无数据源时不做处理
if (!sourceData) {
return;
}
// 暂时存储结果
let mapResult;
/**
* 处理数据映射时仅对两类型数据源做转换,
* 1、数组对象型数据 [{foo:bar}]
* 2、对象型数据 {foo:bar}
* 3、字符串型数据直接转换
*/
// 1、数组对象型数据
if (
Object.prototype.toString.call(sourceData) ===
'[object Array]'
) {
mapResult = [];
sourceData.forEach((itemArgMap: any) => {
if (
Object.prototype.toString.call(itemArgMap) ===
'[object Object]'
) {
const tempData = {};
for (const key in argMap) {
const orderKey = argMap[key];
// 当前项数据存在时
tempData[key] =
itemArgMap[orderKey] ||
// 当前项数据不存在时从运行时取数据,运行时无数据时返回orderKey字符
getArgumentsItem({
fieldName: `${orderKey}`,
data: orderKey,
type: 'string',
}, itemArgMap);
}
mapResult.push(tempData);
}
});
}
// 2、对象型数据
if (
Object.prototype.toString.call(sourceData) ===
'[object Object]'
) {
mapResult = {};
for (const key in argMap) {
if (Object.prototype.hasOwnProperty.call(argMap, key)) {
const orderKey = argMap[key];
mapResult[key] = sourceData[orderKey] ||
// 当前项数据不存在时从运行时取数据,运行时无数据时返回orderKey字符
getArgumentsItem({
fieldName: `${orderKey}`,
data: orderKey,
type: 'string',
}, sourceData);
}
}
}
// 3、字符串型数据
if (
Object.prototype.toString.call(sourceData) ===
'[object String]'
) {
for (const key in argMap) {
if (Object.prototype.hasOwnProperty.call(argMap, key)) {
mapResult = sourceData;
}
}
}
// 赋值
if (mapResult) {
lodash.set(body, target, mapResult);
}
});
}
return body;
}
throw res;
}