2018-08-10 12:49:26 +02:00
|
|
|
// Copyright BigchainDB GmbH and BigchainDB contributors
|
|
|
|
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
|
|
|
|
// Code is Apache-2.0 and docs are CC-BY-4.0
|
|
|
|
|
2021-03-09 07:51:36 +01:00
|
|
|
import 'core-js/features/object/entries'
|
2017-06-12 16:57:29 +02:00
|
|
|
import decamelize from 'decamelize'
|
|
|
|
import queryString from 'query-string'
|
2017-04-26 15:58:19 +02:00
|
|
|
|
|
|
|
/**
|
2018-05-14 17:14:40 +02:00
|
|
|
* @private
|
2017-04-26 15:58:19 +02:00
|
|
|
* 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
|
|
|
|
*
|
2018-05-14 17:14:40 +02:00
|
|
|
* @param {Object} obj Query params dictionary
|
2017-04-26 15:58:19 +02:00
|
|
|
* @param {function} [transform=decamelize] Transform function for each of the param keys
|
|
|
|
* @return {string} Query param string
|
|
|
|
*/
|
|
|
|
export default function stringifyAsQueryParam(obj, transform = decamelize) {
|
|
|
|
if (!obj || typeof obj !== 'object' || !Object.keys(obj).length) {
|
2017-06-12 16:57:29 +02:00
|
|
|
return ''
|
2017-04-26 15:58:19 +02:00
|
|
|
}
|
|
|
|
|
2021-03-09 07:51:36 +01:00
|
|
|
const transformedKeysObj = Object.entries(obj).reduce((paramsObj, [key, value]) => {
|
2017-06-12 16:57:29 +02:00
|
|
|
paramsObj[transform(key)] = value
|
|
|
|
return paramsObj
|
|
|
|
}, {})
|
2017-04-26 15:58:19 +02:00
|
|
|
|
2017-06-12 16:57:29 +02:00
|
|
|
return `?${queryString.stringify(transformedKeysObj)}`
|
|
|
|
}
|