datasquirel/package-shared/utils/serialize-query.js

30 lines
770 B
JavaScript
Raw Normal View History

2024-12-10 14:20:48 +00:00
// @ts-check
2024-12-12 13:38:37 +00:00
const EJSON = require("./ejson");
2024-12-10 14:20:48 +00:00
/** @type {import("../types").SerializeQueryFnType} */
function serializeQuery({ query }) {
let str = "?";
const keys = Object.keys(query);
/** @type {string[]} */
const queryArr = [];
2024-12-12 13:38:37 +00:00
2024-12-10 14:20:48 +00:00
keys.forEach((key) => {
if (!key || !query[key]) return;
2024-12-12 13:38:37 +00:00
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)}`);
}
2024-12-10 14:20:48 +00:00
});
2024-12-12 13:38:37 +00:00
2024-12-10 14:20:48 +00:00
str += queryArr.join("&");
return str;
}
module.exports = serializeQuery;