@chubbyts/chubbyts-decode-encode
Version:
A simple decode/encode solution for json / jsonx / url-encoded / xml / yaml.
35 lines (34 loc) • 985 B
JavaScript
import { parse } from 'qs';
import { isArray, isObject } from '../index.js';
const decodeValue = (value) => {
if (isObject(value)) {
return Object.fromEntries(Object.entries(value).map(([subKey, subValue]) => [subKey, decodeValue(subValue)]));
}
if (isArray(value)) {
return value.map(decodeValue);
}
if (value === 'null') {
return null;
}
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
const integer = parseInt(value, 10);
if (!isNaN(integer) && integer.toString() === value) {
return integer;
}
const float = parseFloat(value);
if (!isNaN(float) && float.toString() === value) {
return float;
}
return value;
};
export const createUrlEncodedTypeDecoder = () => {
return {
decode: (encodedData) => decodeValue(parse(encodedData, { depth: 100 })),
contentType: 'application/x-www-form-urlencoded',
};
};