All files / src/utils/generators queryGenerator.ts

100% Statements 13/13
90% Branches 9/10
100% Functions 5/5
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31              27x 172x 230x 230x       27x 235x   643x     643x 643x       27x 235x 235x 235x    
type TMultipleBySameName = Record<string, any>;
 
export type TQueryParams = Record<
  string,
  string | number | null | TMultipleBySameName
>;
 
const reduceMultipleBySameKey = (obj: TMultipleBySameName) => {
  return Object.entries(obj).reduce((acc, [key, value], index) => {
    const separator = index ? ";" : "";
    return acc + separator + `${key}:${value}`;
  }, "");
};
 
const reduceQueryParams = (params: TQueryParams) => {
  return Object.entries(params).reduce((acc, [key, values], index) => {
    const paramValue =
      typeof values !== "object" || !values
        ? values
        : reduceMultipleBySameKey(values);
    const separator = index ? "&" : "";
    return acc + separator + `${key}=${encodeURIComponent(`${paramValue}`)}`;
  }, "");
};
 
export const queryGenerator = (baseURL: string, params?: TQueryParams) => {
  const formattedParams = params ? "?" + reduceQueryParams(params) : "";
  const url = baseURL + formattedParams;
  return url;
};