2019-11-19 07:30:42 +03:00
|
|
|
import {formatISO} from './date'
|
|
|
|
|
2020-07-02 11:21:59 +03:00
|
|
|
let abortController = new AbortController()
|
|
|
|
|
2019-11-19 07:30:42 +03:00
|
|
|
function serialize(obj) {
|
|
|
|
var str = [];
|
|
|
|
for (var p in obj)
|
|
|
|
if (obj.hasOwnProperty(p)) {
|
|
|
|
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
|
|
|
|
}
|
|
|
|
return str.join("&");
|
|
|
|
}
|
|
|
|
|
2020-07-02 11:21:59 +03:00
|
|
|
export function cancelAll() {
|
|
|
|
abortController.abort()
|
|
|
|
abortController = new AbortController()
|
|
|
|
}
|
|
|
|
|
2020-10-28 12:09:04 +03:00
|
|
|
function serializeFilters(filters) {
|
|
|
|
const cleaned = {}
|
|
|
|
Object.entries(filters).forEach(([key, val]) => val ? cleaned[key] = val : null);
|
|
|
|
return JSON.stringify(cleaned)
|
|
|
|
}
|
|
|
|
|
2020-01-13 16:46:28 +03:00
|
|
|
export function serializeQuery(query, extraQuery=[]) {
|
2020-10-28 12:09:04 +03:00
|
|
|
const queryObj = {}
|
|
|
|
if (query.period) { queryObj.period = query.period }
|
|
|
|
if (query.date) { queryObj.date = formatISO(query.date) }
|
|
|
|
if (query.from) { queryObj.from = formatISO(query.from) }
|
|
|
|
if (query.to) { queryObj.to = formatISO(query.to) }
|
|
|
|
if (query.filters) { queryObj.filters = serializeFilters(query.filters) }
|
|
|
|
Object.assign(queryObj, ...extraQuery)
|
2019-11-19 07:30:42 +03:00
|
|
|
|
2020-10-28 12:09:04 +03:00
|
|
|
return '?' + serialize(queryObj)
|
2020-01-13 16:16:35 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
export function get(url, query, ...extraQuery) {
|
|
|
|
url = url + serializeQuery(query, extraQuery)
|
2020-07-02 11:21:59 +03:00
|
|
|
return fetch(url, {signal: abortController.signal})
|
2020-05-26 13:40:49 +03:00
|
|
|
.then( response => {
|
|
|
|
if (!response.ok) { throw response }
|
|
|
|
return response.json()
|
|
|
|
})
|
2019-11-19 07:30:42 +03:00
|
|
|
}
|