1
0
mirror of https://github.com/ascribe/onion.git synced 2024-12-23 09:50:31 +01:00
onion/js/utils/fetch_api_utils.js

63 lines
1.4 KiB
JavaScript
Raw Normal View History

2015-06-02 13:42:17 +02:00
import { sanitize } from './general_utils';
2015-05-19 17:01:28 +02:00
// TODO: Create Unittests that test all functions
/**
* Takes a key-value object 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!
*
*/
export function argsToQueryParams(obj) {
2015-05-19 17:01:28 +02:00
obj = sanitize(obj);
2015-05-19 17:01:28 +02:00
return Object
.keys(obj)
.map((key, i) => {
let s = '';
if(i === 0) {
s += '?';
} else {
s += '&';
}
let snakeCaseKey = key.replace(/[A-Z]/, (match) => '_' + match.toLowerCase());
return s + snakeCaseKey + '=' + encodeURIComponent(obj[key]);
})
.join('');
};
2015-05-21 12:12:25 +02:00
/**
* Takes a string and a boolean and generates a string query parameter for
* an API call.
*/
export function generateOrderingQueryParams(orderBy, orderAsc) {
let interpolation = '';
2015-05-21 12:12:25 +02:00
if(!orderAsc) {
interpolation += '-';
}
2015-05-21 12:12:25 +02:00
return interpolation + orderBy;
};
2015-05-27 17:33:15 +02:00
export function status(response) {
if (response.status >= 200 && response.status < 300) {
return response
}
throw new Error(response.json())
};