Skip to content

Commit

Permalink
refactor: optimize encodeParams
Browse files Browse the repository at this point in the history
  • Loading branch information
suhaotian committed Jul 9, 2024
1 parent 2a28864 commit 7d97d20
Showing 1 changed file with 12 additions and 30 deletions.
42 changes: 12 additions & 30 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,22 @@ export function encodeParams<T = any>(
const encodedParams = [];
const encodeURIFn = encodeURI ? encodeURIComponent : (v: string) => v;
const paramsIsArray = Array.isArray(params);
const getKey = (key: string) => {
if (options?.allowDots && !paramsIsArray) return `.${key}`;
if (paramsIsArray) {
if (options?.arrayFormat === 'brackets') {
return `[]`;
} else if (options?.arrayFormat === 'repeat') {
return ``;
}
}
return `[${key}]`;
};
for (const key in params) {
if (Object.prototype.hasOwnProperty.call(params, key)) {
let value = (params as any)[key];
if (value !== undefinedValue) {
const encodedKey = encodeKey(
parentKey,
key,
paramsIsArray,
options?.arrayFormat,
options?.allowDots
);
const encodedKey = parentKey ? `${parentKey}${getKey(key)}` : (key as string);

if (value instanceof Date) {
value = options?.serializeDate ? options?.serializeDate(value) : value.toISOString();
Expand All @@ -49,29 +54,6 @@ export function encodeParams<T = any>(
return encodedParams.join('&');
}

const encodeKey = (
parentKey: string | null,
key: string,
isArray: boolean,
arrayFormat?: 'indices' | 'brackets' | 'repeat',
allowDots?: boolean
) => {
if (!parentKey) return key;
// arrayFormat = arrayFormat || 'indices';
const getKey = (key: string) => {
if (allowDots && !isArray) return `.${key}`;
if (isArray) {
if (arrayFormat === 'brackets') {
return `[]`;
} else if (arrayFormat === 'repeat') {
return ``;
}
}
return `[${key}]`;
};
return `${parentKey}${getKey(key)}`;
};

export function trimUndefined(obj: any): any {
if (Array.isArray(obj)) {
return obj.map(trimUndefined);
Expand Down

0 comments on commit 7d97d20

Please sign in to comment.