All files params.ts

100% Statements 87/87
100% Branches 30/30
100% Functions 4/4
100% Lines 87/87

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 881x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 22x 22x 22x 20x 22x 22x 22x 14x 22x 22x 22x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 30x 30x 30x 22x 22x 22x 22x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x 1x 1x 4x 5x 3x 3x 3x 2x 5x 2x 2x 2x  
import set from 'lodash/set'
import { serialize as objectToFormData } from 'object-to-formdata'
 
/**
 * Transforms an object to HTTP query string.
 * Returns a query string suitable for use in URL.
 * Does not include the question mark.
 *
 * @export Function
 * @param {Record<string, any>} input
 * @returns {String} String
 */
export function serialize(input: Record<string, any> = {}): string {
  const params = new URLSearchParams()
 
  const iterate = (obj: Record<string, any>, pre?: string) => {
    const keys = Object.keys(obj)
 
    keys.forEach((k) => {
      const param = obj[k]
 
      if (param === null || param === undefined) return null
 
      const key = pre ? `${pre}[${k}]` : k
 
      if (typeof param === 'object') return iterate(param, key)
 
      const val = Number.isFinite(param) ? param.toString() : param
 
      return val && params.set(key, val)
    })
 
    const qs = params.toString()
    const result = decodeURIComponent(qs)
 
    return result
  }
 
  return iterate(input)
}
 
/**
 * Transforms URL query string to an object.
 *
 * @export Function
 * @param {String} input
 * @returns {Record<string, any>} Object
 */
export function parse(input: string = ''): Record<string, any> {
  const data: Record<string, any> = {}
  const params = new URLSearchParams(input)
 
  Array.from(params.entries()).forEach(([key, val]) => {
    const value = !val ? null : /^\d+$/.test(val) ? Number(val) : val
 
    if (!key.includes('[')) return (data[key] = value)
 
    const path = key.replace(/\]/g, '').split('[')
 
    return set(data, path, value)
  })
 
  return data
}
 
/**
 * Transforms query string or object into FormData.
 *
 * @export Function
 * @param {*} input
 * @returns {*} *
 */
export function form(input: any): any {
  if (typeof FormData === 'undefined') {
    console.error('FormData not supported')
    return input
  }
 
  if (input instanceof FormData) return input
 
  if (typeof HTMLFormElement !== 'undefined')
    if (input instanceof HTMLFormElement) return new FormData(input)
 
  if (typeof input === 'string') input = parse(input)
 
  return objectToFormData(input)
}