All files / src/apis/shared querystring.ts

100% Statements 16/16
100% Branches 10/10
100% Functions 2/2
100% Lines 16/16

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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 556x                       97x                           6x 89x   89x 69x 49x 49x     20x 8x     12x     28x 13x   15x     13x       89x    
import { URLSearchParameters } from "./url-globals";
import type { AnyRecord } from "./types";
 
type Primitive = string | number | boolean;
 
/**
 *
 *
 * @param {unknown} value
 * @return {boolean} value is Primitive
 */
function isPrimitive(value: unknown): value is Primitive {
  return (
    typeof value === "string" ||
    typeof value === "number" ||
    typeof value === "boolean" ||
    typeof value === "bigint"
  );
}
 
/**
 * Создаёт строку запроса, в формате, который понимает QIWI
 *
 * @param {AnyRecord} object Объект для преобразования
 * @return {string}
 */
export function formatQuerystring(object: AnyRecord): string {
  const parameters = new URLSearchParameters();
 
  for (const [key, value] of Object.entries(object)) {
    if (isPrimitive(value)) {
      parameters.set(key, String(value));
      continue;
    }
 
    if (!(typeof value === "object" && value)) {
      continue;
    }
 
    for (const [subKey, subValue] of Object.entries(value)) {
      let string: string;
 
      if (isPrimitive(subValue)) {
        string = String(subValue);
      } else {
        continue;
      }
 
      parameters.set(`${key}[${subKey}]`, string);
    }
  }
 
  return parameters.toString();
}