apiv1-client.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import * as urljoin from 'url-join';
  2. import axios from '~/utils/axios';
  3. const apiv1Root = '/_api';
  4. // get csrf token from body element
  5. const body = document.querySelector('body');
  6. const csrfToken = body?.dataset.csrftoken;
  7. type ParamWithCsrfKey = {
  8. _csrf: string,
  9. }
  10. class Apiv1ErrorHandler extends Error {
  11. code;
  12. data;
  13. constructor(message = '', code = '', data = '') {
  14. super();
  15. this.message = message;
  16. this.code = code;
  17. this.data = data;
  18. }
  19. }
  20. export async function apiRequest(method: string, path: string, params: unknown): Promise<unknown> {
  21. const res = await axios[method](urljoin(apiv1Root, path), params);
  22. if (res.data.ok) {
  23. return res.data;
  24. }
  25. // Return error code if code is exist
  26. if (res.data.code != null) {
  27. const error = new Apiv1ErrorHandler(res.data.error, res.data.code, res.data.data);
  28. throw error;
  29. }
  30. throw new Error(res.data.error);
  31. }
  32. export async function apiGet(path: string, params: unknown = {}): Promise<unknown> {
  33. return apiRequest('get', path, { params });
  34. }
  35. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  36. export async function apiPost(path: string, params: any & ParamWithCsrfKey = {}): Promise<unknown> {
  37. if (params._csrf == null) {
  38. params._csrf = csrfToken;
  39. }
  40. return apiRequest('post', path, params);
  41. }
  42. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  43. export async function apiDelete(path: string, params: any & ParamWithCsrfKey = {}): Promise<unknown> {
  44. if (params._csrf == null) {
  45. params._csrf = csrfToken;
  46. }
  47. return apiRequest('delete', path, { data: params });
  48. }