2019-06-23 03:40:53 +03:00
|
|
|
import { RootStore } from "./store";
|
2019-06-22 18:52:24 +03:00
|
|
|
const apiUrl = process.env.API_URL;
|
|
|
|
|
|
|
|
type QueryParamObject = { [key: string]: string | null };
|
|
|
|
|
2019-07-11 12:23:57 +03:00
|
|
|
export class ApiError extends Error {
|
|
|
|
protected body: object;
|
|
|
|
protected status: number;
|
|
|
|
protected res: Response;
|
|
|
|
|
|
|
|
constructor(message: string, body: object, status: number, res: Response) {
|
|
|
|
super(message);
|
|
|
|
this.body = body;
|
|
|
|
this.status = status;
|
|
|
|
this.res = res;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-22 18:52:24 +03:00
|
|
|
function buildQueryString(params: QueryParamObject) {
|
|
|
|
if (Object.keys(params).length === 0) return "";
|
|
|
|
|
|
|
|
return (
|
|
|
|
"?" +
|
|
|
|
Array.from(Object.entries(params))
|
|
|
|
.map(pair => `${encodeURIComponent(pair[0])}=${encodeURIComponent(pair[1] || "")}`)
|
|
|
|
.join("&")
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function request(resource, fetchOpts: RequestInit = {}) {
|
2019-07-11 12:23:57 +03:00
|
|
|
return fetch(`${apiUrl}/${resource}`, fetchOpts).then(async res => {
|
|
|
|
if (!res.ok) {
|
|
|
|
const body = await res.json();
|
|
|
|
throw new ApiError(res.statusText, body, res.status, res);
|
|
|
|
}
|
|
|
|
|
|
|
|
return res.json();
|
|
|
|
});
|
2019-06-22 18:52:24 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
export function get(resource: string, params: QueryParamObject = {}) {
|
2019-06-23 03:40:53 +03:00
|
|
|
const headers: Record<string, string> = RootStore.state.auth.apiKey
|
|
|
|
? { "X-Api-Key": RootStore.state.auth.apiKey }
|
|
|
|
: {};
|
2019-06-22 18:52:24 +03:00
|
|
|
return request(resource + buildQueryString(params), {
|
|
|
|
method: "GET",
|
|
|
|
headers,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function post(resource: string, params: QueryParamObject = {}) {
|
2019-06-23 03:40:53 +03:00
|
|
|
const headers: Record<string, string> = RootStore.state.auth.apiKey
|
|
|
|
? { "X-Api-Key": RootStore.state.auth.apiKey }
|
|
|
|
: {};
|
2019-07-11 12:23:57 +03:00
|
|
|
return request(resource, {
|
2019-06-22 18:52:24 +03:00
|
|
|
method: "POST",
|
|
|
|
body: JSON.stringify(params),
|
|
|
|
headers: {
|
|
|
|
...headers,
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|