Skip to content

Commit

Permalink
fix: simplify build query string util
Browse files Browse the repository at this point in the history
  • Loading branch information
tada5hi committed May 18, 2023
1 parent c4ba303 commit 7e7eb28
Showing 1 changed file with 20 additions and 20 deletions.
40 changes: 20 additions & 20 deletions src/utils/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 7e7eb28

Please sign in to comment.