datasquirel/package-shared/utils/serialize-query.js
Benjamin Toby 2a4e111160 Updates
2024-12-12 14:38:37 +01:00

30 lines
770 B
JavaScript

// @ts-check
const EJSON = require("./ejson");
/** @type {import("../types").SerializeQueryFnType} */
function serializeQuery({ query }) {
let str = "?";
const keys = Object.keys(query);
/** @type {string[]} */
const queryArr = [];
keys.forEach((key) => {
if (!key || !query[key]) return;
const value = query[key];
if (typeof value === "object") {
const jsonStr = EJSON.stringify(value);
queryArr.push(`${key}=${encodeURIComponent(String(jsonStr))}`);
} else if (typeof value === "string" || typeof value === "number") {
queryArr.push(`${key}=${encodeURIComponent(value)}`);
}
});
str += queryArr.join("&");
return str;
}
module.exports = serializeQuery;