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

43 lines
1.1 KiB
TypeScript
Raw Normal View History

2025-01-10 19:10:28 +00:00
import EJSON from "./ejson";
2024-12-10 14:20:48 +00:00
2025-01-10 19:10:28 +00:00
/**
* # Serialize Query
*/
export default function serializeQuery(query: any): string {
2024-12-10 14:20:48 +00:00
let str = "?";
2024-12-12 13:43:25 +00:00
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;
}
2024-12-10 14:20:48 +00:00
const keys = Object.keys(query);
2025-01-10 19:10:28 +00:00
const queryArr: string[] = [];
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-28 15:23:31 +00:00
} else {
queryArr.push(`${key}=${String(value)}`);
2024-12-12 13:38:37 +00:00
}
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;
}