UNPKG

nested-query-params

Version:
41 lines 1.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.printQueryParamVal = exports.printQueryParams = exports.printQuery = void 0; /** * Serializes the given object to a valid query parameter string. Supported * types are Arrays, Objects and basic value types. Heavily inspired by * {@link https://github.com/rails/rails/blob/main/activesupport/lib/active_support/core_ext/object/to_query.rb#L61-L89|Rack's nested query parser}. * * @example * // returns "?one[two]=3"; * parseQuery({ one: { two: "3" } }); */ function printQuery(query, ns) { return "?" + printQueryParams(query, ns); } exports.printQuery = printQuery; function printQueryParams(query, ns) { const makeKey = (key) => (ns ? `${ns}[${key}]` : key); return Object.entries(query) .map(([key, val]) => printQueryParamVal(val, makeKey(key))) .join("&"); } exports.printQueryParams = printQueryParams; function printQueryParamVal(query, ns) { if (typeof query === "object") { if (!Array.isArray(query)) { return printQueryParams(query, ns); } const prefix = `${ns}[]`; if (query.length === 0) { return printQueryParamVal("", prefix); } return query.map((q) => printQueryParamVal(q, prefix)).join("&"); } return `${encode(ns)}=${encode(query)}`; } exports.printQueryParamVal = printQueryParamVal; function encode(str) { return encodeURIComponent(str); } //# sourceMappingURL=print.js.map