All files / src stringify_as_query_param.js

90.91% Statements 10/11
77.78% Branches 7/9
100% Functions 2/2
90% Lines 9/10
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 434x 4x 4x                                                       48x 48x       150x 50x 50x     48x    
import coreObjectEntries from 'core-js/library/fn/object/entries'
import decamelize from 'decamelize'
import queryString from 'query-string'
 
 
/**
 * imported from https://github.com/bigchaindb/js-utility-belt/
 *
 * Takes a key-value dictionary (ie. object) and converts it to a query-parameter string that you
 * can directly append into a URL.
 *
 * Extends queryString.stringify by allowing you to specify a `transform` function that will be
 * invoked on each of the dictionary's keys before being stringified into the query-parameter
 * string.
 *
 * By default `transform` is `decamelize`, so a dictionary of the form:
 *
 *   {
 *      page: 1,
 *      pageSize: 10
 *   }
 *
 * will be converted to a string like:
 *
 *   ?page=1&page_size=10
 *
 * @param  {object}   obj                    Query params dictionary
 * @param  {function} [transform=decamelize] Transform function for each of the param keys
 * @return {string}                          Query param string
 */
export default function stringifyAsQueryParam(obj, transform = decamelize) {
    Iif (!obj || typeof obj !== 'object' || !Object.keys(obj).length) {
        return ''
    }
 
    const transformedKeysObj = coreObjectEntries(obj).reduce((paramsObj, [key, value]) => {
        paramsObj[transform(key)] = value
        return paramsObj
    }, {})
 
    return `?${queryString.stringify(transformedKeysObj)}`
}