dsql-admin/dsql-app/package-shared/utils/serialize-query.js

44 lines
1.1 KiB
JavaScript
Raw Normal View History

2024-12-15 11:27:16 +00:00
// @ts-check
const EJSON = require("./ejson");
/** @type {import("../types").SerializeQueryFnType} */
function serializeQuery(query) {
let str = "?";
if (typeof query !== "object") {
console.log("Invalid Query type");
return str;
}
if (Array.isArray(query)) {
console.log("Query is an Array. This is invalid.");
return str;
}
if (!query) {
console.log("No Query provided.");
return 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;