35 lines
No EOL
1 KiB
TypeScript
35 lines
No EOL
1 KiB
TypeScript
|
|
type Representable = string|number|boolean;
|
|
|
|
type ToQueryStringA = {
|
|
[name:string]:Representable|Representable[]|undefined
|
|
};
|
|
|
|
export const toQueryString = (obj:ToQueryStringA)=> {
|
|
return Object.entries(obj)
|
|
.filter((e): e is [string,Representable|Representable[]] =>
|
|
e[1] !== undefined)
|
|
.map(e =>
|
|
e[1] instanceof Array
|
|
? e[1].map(f=>`${e[0]}[]=${encodeURIComponent(f)}`).join('&')
|
|
: `${e[0]}=${encodeURIComponent(e[1])}`)
|
|
.join('&');
|
|
}
|
|
export const QueryStringToMap = (query:string) =>{
|
|
const keyValue = query.slice(query.indexOf("?")+1).split("&");
|
|
const param:{[k:string]:string|string[]} = {};
|
|
keyValue.forEach((p)=>{
|
|
const [k,v] = p.split("=");
|
|
if(k.endsWith("[]")){
|
|
let arr = param[k];
|
|
if(arr instanceof Array){
|
|
arr.push(v);
|
|
}
|
|
else{
|
|
param[k] = [v];
|
|
}
|
|
}
|
|
else param[k] = v;
|
|
});
|
|
return param;
|
|
} |