UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

55 lines (54 loc) 2.31 kB
import { isString } from '../guards/primitives.js'; import { flattenObjectKeyValue } from '../object/objectify.js'; import { parseObjectValues } from '../object/sanitize.js'; import { deepParsePrimitives } from '../utils/index.js'; export function generateQueryParams(params = {}) { const flattenedParams = flattenObjectKeyValue(params); const queryParams = Object.entries(flattenedParams) ?.filter(([_, value]) => value != null && !(isString(value) && value?.trim() === '')) ?.flatMap(([key, value]) => Array.isArray(value) ? value ?.filter((v) => v != null && !(isString(v) && v.trim() === '')) ?.map((v) => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`) : `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`) .join('&'); return queryParams ? `?${queryParams}` : ''; } export function getQueryParams() { return Object.fromEntries(new URLSearchParams(window?.location?.search)); } export function updateQueryParam(key, value) { const url = new URL(window.location.href); url.searchParams.set(key, value); window.history.replaceState({}, '', url?.toString()); } export function parseQueryString(query, parsePrimitives = true) { const params = new URLSearchParams(query.startsWith('?') ? query.slice(1) : query); const entries = {}; for (const [key, value] of params.entries()) { if (key in entries) { const current = entries[key]; const array = Array.isArray(current) ? [...current, value] : [current, value]; entries[key] = parsePrimitives ? deepParsePrimitives(array) : array; } else { entries[key] = value; } } return (parsePrimitives ? parseObjectValues(entries) : entries); } export function parseQueryStringLiteral(query) { const params = new URLSearchParams(query.startsWith('?') ? query.slice(1) : query); const entries = {}; for (const [key, value] of params.entries()) { if (key in entries) { const current = entries[key]; const array = Array.isArray(current) ? [...current, value] : [current, value]; entries[key] = array; } else { entries[key] = value; } } return entries; }