apiv1-client.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. constructor(message = '', code = '') {
  13. super();
  14. this.message = message;
  15. this.code = code;
  16. }
  17. }
  18. export async function apiRequest(method: string, path: string, params: unknown): Promise<unknown> {
  19. const res = await axios[method](urljoin(apiv1Root, path), params);
  20. if (res.data.ok) {
  21. return res.data;
  22. }
  23. // Return error code if code is exist
  24. if (res.data.code != null) {
  25. const error = new Apiv1ErrorHandler(res.data.error, res.data.code);
  26. throw error;
  27. }
  28. throw new Error(res.data.error);
  29. }
  30. export async function apiGet(path: string, params: unknown = {}): Promise<unknown> {
  31. return apiRequest('get', path, { params });
  32. }
  33. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  34. export async function apiPost(path: string, params: any & ParamWithCsrfKey = {}): Promise<unknown> {
  35. if (params._csrf == null) {
  36. params._csrf = csrfToken;
  37. }
  38. return apiRequest('post', path, params);
  39. }
  40. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  41. export async function apiDelete(path: string, params: any & ParamWithCsrfKey = {}): Promise<unknown> {
  42. if (params._csrf == null) {
  43. params._csrf = csrfToken;
  44. }
  45. return apiRequest('delete', path, { data: params });
  46. }