Skip to content

Commit

Permalink
fix: update url formater to handle all cases (#332)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxmousse committed Dec 14, 2021
1 parent 47793f9 commit 7ad0b6f
Showing 1 changed file with 29 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/**
/**
* From https://github.com/sindresorhus/type-fest/
* Matches a JSON object.
* This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from.
Expand Down Expand Up @@ -28,22 +28,44 @@ export type URLSearchParamsType =
| string
| string[][]
| URLSearchParams
// | Date
| JsonObject
| JsonObject[];

export function formatUrlParams(params: JsonObject): Record<string, string> {
return Object.entries(params).reduce((acc, [key, value]) => {
if (value === undefined) return acc;
// Ignore value if it is null or undefined
if (value === undefined || value === null) return acc;

let formatedValue: string;

if (typeof value === 'string') acc[key] = value;
// String value is not modified
if (typeof value === 'string') {
formatedValue = value;

if (typeof value === 'boolean' || typeof value === 'number')
acc[key] = `${value}`;
// Boolean and number are turned into string
} else if (typeof value === 'boolean' || typeof value === 'number') {
formatedValue = `${value}`;

if (value instanceof Date) acc[key] = value.toISOString();
// Date is turn into an ISO string
} else if (value instanceof Date) {
formatedValue = value.toISOString();

if (value !== null && typeof value === 'object')
// Object is stringified
} else if (typeof value === 'object' || Array.isArray(value)) {
formatedValue = JSON.stringify(params[key]);
acc[key] = JSON.stringify(params[key]);
return acc;

// This should never happen as all cases are handled before
} else {
throw new Error(
`Value ${value} can be formated to an url parameter as its type is not handled`,
);
}

// Add the formated key to the accumulator
acc[key] = formatedValue;

return acc;
}, {} as Record<string, string>);
Expand All @@ -54,11 +76,9 @@ export function getUrlSearchParams(init: URLSearchParamsType) {
if (typeof params === 'string' || params instanceof URLSearchParams) {
return new URLSearchParams(params);
}

if (params !== null && typeof params === 'object' && !Array.isArray(params)) {
return new URLSearchParams(formatUrlParams(params));
}

return new URLSearchParams(JSON.stringify(params));
}

Expand All @@ -72,9 +92,6 @@ export function getUrl(
apiUrl,
);
const queries = getUrlSearchParams(params);

url.search = queries.toString();

return url;
}

0 comments on commit 7ad0b6f

Please sign in to comment.