2023-03-14 13:18:55 +00:00
|
|
|
/**
|
|
|
|
* Copyright (c) HashiCorp, Inc.
|
2023-08-11 13:12:13 +00:00
|
|
|
* SPDX-License-Identifier: BUSL-1.1
|
2023-03-14 13:18:55 +00:00
|
|
|
*/
|
|
|
|
|
2022-09-15 08:43:17 +00:00
|
|
|
export default function (encode = encodeURIComponent) {
|
2020-07-07 18:58:46 +00:00
|
|
|
return function stringify(obj, parent) {
|
|
|
|
return Object.entries(obj)
|
2022-09-15 08:43:17 +00:00
|
|
|
.reduce(function (prev, [key, value], i) {
|
2020-07-07 18:58:46 +00:00
|
|
|
// if the value is undefined do nothing
|
|
|
|
if (typeof value === 'undefined') {
|
|
|
|
return prev;
|
|
|
|
}
|
|
|
|
let prop = encode(key);
|
|
|
|
// if we have a parent, prefix the property with that
|
|
|
|
if (typeof parent !== 'undefined') {
|
|
|
|
prop = `${parent}[${prop}]`;
|
|
|
|
}
|
|
|
|
// if the value is null just print the prop
|
|
|
|
if (value === null) {
|
|
|
|
return prev.concat(prop);
|
|
|
|
}
|
|
|
|
// anything nested, recur
|
|
|
|
if (typeof value === 'object') {
|
|
|
|
return prev.concat(stringify(value, prop));
|
|
|
|
}
|
|
|
|
// anything else print prop=value
|
|
|
|
return prev.concat(`${prop}=${encode(value)}`);
|
|
|
|
}, [])
|
|
|
|
.join('&');
|
|
|
|
};
|
|
|
|
}
|