analytics/assets/js/dashboard/api.js
Mackenzie 9c2fd9aca5
1. Remove the "airbnb" eslint plugin since it conflicts with prettier (#1374)
and so was just annoying
2. Get rid of all existing ESLint errors.
2a. Turned off `react/display-name` because I couldn't figure out how to
make that wrapped component have a display name. If anyone can figure it
out, that'd be great, because that makes things nicer when using the
React debugger.
2b. The part where it says `plausible()` is undefined in `app.js` is
bothering me. I disabled the check because I can't figure out where that
actually comes from to put in the proper import.
2c. Told ESLint we're using Babel.
3. Added `npm run format` and `npm run lint` commands.
2021-10-11 14:48:19 +02:00

64 lines
1.8 KiB
JavaScript

import {formatISO} from './date'
let abortController = new AbortController()
let SHARED_LINK_AUTH = null
class ApiError extends Error {
constructor(message) {
super(message);
this.name = "ApiError";
}
}
function serialize(obj) {
var str = [];
for (var p in obj)
/* eslint-disable-next-line no-prototype-builtins */
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
export function setSharedLinkAuth(auth) {
SHARED_LINK_AUTH = auth
}
export function cancelAll() {
abortController.abort()
abortController = new AbortController()
}
function serializeFilters(filters) {
const cleaned = {}
Object.entries(filters).forEach(([key, val]) => val ? cleaned[key] = val : null);
return JSON.stringify(cleaned)
}
export function serializeQuery(query, extraQuery=[]) {
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) }
if (SHARED_LINK_AUTH) { queryObj.auth = SHARED_LINK_AUTH }
Object.assign(queryObj, ...extraQuery)
return '?' + serialize(queryObj)
}
export function get(url, query={}, ...extraQuery) {
const headers = SHARED_LINK_AUTH ? {'X-Shared-Link-Auth': SHARED_LINK_AUTH} : {}
url = url + serializeQuery(query, extraQuery)
return fetch(url, {signal: abortController.signal, headers: headers})
.then( response => {
if (!response.ok) {
return response.json().then((msg) => {
throw new ApiError(msg.error)
})
}
return response.json()
})
}