2016-02-01 14:47:51 +01:00
|
|
|
'use strict';
|
2015-10-30 17:43:20 +01:00
|
|
|
|
|
|
|
import camelCase from 'camelcase';
|
2015-11-02 18:29:06 +01:00
|
|
|
import decamelize from 'decamelize';
|
2016-01-05 14:13:46 +01:00
|
|
|
import queryString from 'query-string';
|
2015-10-30 17:43:20 +01:00
|
|
|
|
|
|
|
import { sanitize } from './general_utils';
|
|
|
|
|
|
|
|
// TODO: Create Unittests that test all functions
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Takes a key-value dictionary of this form:
|
|
|
|
*
|
|
|
|
* {
|
|
|
|
* 'page': 1,
|
|
|
|
* 'pageSize': 10
|
|
|
|
* }
|
|
|
|
*
|
|
|
|
* and converts it to a query-parameter, which you can append to your URL.
|
|
|
|
* The return looks like this:
|
|
|
|
*
|
|
|
|
* ?page=1&page_size=10
|
|
|
|
*
|
|
|
|
* CamelCase gets converted to snake_case!
|
|
|
|
*
|
|
|
|
* @param {object} obj Query params dictionary
|
|
|
|
* @return {string} Query params string
|
|
|
|
*/
|
|
|
|
export function argsToQueryParams(obj) {
|
|
|
|
const sanitizedObj = sanitize(obj);
|
|
|
|
const queryParamObj = {};
|
|
|
|
|
|
|
|
Object
|
|
|
|
.keys(sanitizedObj)
|
|
|
|
.forEach((key) => {
|
2015-11-02 18:29:06 +01:00
|
|
|
queryParamObj[decamelize(key)] = sanitizedObj[key];
|
2015-10-30 17:43:20 +01:00
|
|
|
});
|
|
|
|
|
2016-01-05 14:13:46 +01:00
|
|
|
return '?' + queryString.stringify(queryParamObj);
|
2015-10-30 17:43:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the current url's query params as an key-val dictionary.
|
|
|
|
* snake_case gets converted to CamelCase!
|
|
|
|
* @return {object} Query params dictionary
|
|
|
|
*/
|
|
|
|
export function getCurrentQueryParams() {
|
|
|
|
return queryParamsToArgs(window.location.search.substring(1));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Convert the given query param string into a key-val dictionary.
|
|
|
|
* snake_case gets converted to CamelCase!
|
|
|
|
* @param {string} queryParamString Query params string
|
|
|
|
* @return {object} Query params dictionary
|
|
|
|
*/
|
|
|
|
export function queryParamsToArgs(queryParamString) {
|
2016-01-05 14:13:46 +01:00
|
|
|
const queryParamObj = queryString.parse(queryParamString);
|
2015-10-30 17:43:20 +01:00
|
|
|
const camelCaseParamObj = {};
|
|
|
|
|
|
|
|
Object
|
2016-01-05 14:13:46 +01:00
|
|
|
.keys(queryParamObj)
|
2015-10-30 17:43:20 +01:00
|
|
|
.forEach((key) => {
|
2016-01-05 14:13:46 +01:00
|
|
|
camelCaseParamObj[camelCase(key)] = queryParamObj[key];
|
2015-10-30 17:43:20 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
return camelCaseParamObj;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Takes a string and a boolean and generates a string query parameter for
|
|
|
|
* an API call.
|
|
|
|
*/
|
|
|
|
export function generateOrderingQueryParams(orderBy, orderAsc) {
|
|
|
|
let interpolation = '';
|
|
|
|
|
|
|
|
if(!orderAsc) {
|
|
|
|
interpolation += '-';
|
|
|
|
}
|
|
|
|
|
|
|
|
return interpolation + orderBy;
|
|
|
|
}
|