From 7e7eb28372900f4c2c09a99460dfa179fe49b837 Mon Sep 17 00:00:00 2001 From: tada5hi Date: Thu, 18 May 2023 18:31:09 +0200 Subject: [PATCH] fix: simplify build query string util --- src/utils/url.ts | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/utils/url.ts b/src/utils/url.ts index f87460f2..d0aa43b2 100644 --- a/src/utils/url.ts +++ b/src/utils/url.ts @@ -5,43 +5,43 @@ * view the LICENSE file that was distributed with this source code. */ +import { isObject } from 'smob'; + export function buildURLQueryString(data?: any, withQuestionMark = true) { if (typeof data === 'undefined' || data === null) return ''; // If the data is already a string, return it as-is - if (typeof (data) === 'string') return data; + if (typeof data === 'string') return data; // Create a query array to hold the key/value pairs - const query = []; + const query : string[] = []; // Loop through the data object const keys = Object.keys(data); for (let i = 0; i < keys.length; i++) { - if (Object.prototype.hasOwnProperty.call(data, keys[i])) { - let value = data[keys[i]]; - - if (value && typeof value === 'object' && value.constructor === Array) { - value = value.join(','); - } - - if (value && typeof value === 'object' && value.constructor === Object) { - const valueKeys = Object.keys(value); - for (let j = 0; j < valueKeys.length; j++) { - let v: any = value[valueKeys[j]]; + let value = data[keys[i]]; - if (v && typeof v === 'object' && v.constructor === Array) { - v = v.join(','); - } + if (isObject(value)) { + const valueKeys = Object.keys(value); + for (let j = 0; j < valueKeys.length; j++) { + let v = value[valueKeys[j]]; - query.push(`${encodeURIComponent(`${keys[i]}[${valueKeys[j]}]`)}=${encodeURIComponent(v)}`); + if (Array.isArray(v)) { + v = v.join(','); } - continue; + query.push(`${encodeURIComponent(`${keys[i]}[${valueKeys[j]}]`)}=${encodeURIComponent(v)}`); } - // Encode each key and value, concatenate them into a string, and push them to the array - query.push(`${encodeURIComponent(keys[i])}=${encodeURIComponent(value)}`); + continue; } + + if (Array.isArray(value)) { + value = value.join(','); + } + + // Encode each key and value, concatenate them into a string, and push them to the array + query.push(`${encodeURIComponent(keys[i])}=${encodeURIComponent(value)}`); } // Join each item in the array with a `&` and return the resulting string