apiv1-client.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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<T>(method: string, path: string, params: unknown): Promise<T> {
  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<T>(path: string, params: unknown = {}): Promise<T> {
  33. return apiRequest<T>('get', path, { params });
  34. }
  35. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  36. export async function apiPost<T>(path: string, params: any & ParamWithCsrfKey = {}): Promise<T> {
  37. if (params._csrf == null) {
  38. params._csrf = csrfToken;
  39. }
  40. return apiRequest<T>('post', path, params);
  41. }
  42. export async function apiPostForm<T>(path: string, formData: FormData): Promise<T> {
  43. if (formData.get('_csrf') == null && csrfToken != null) {
  44. formData.append('_csrf', csrfToken);
  45. }
  46. return apiPost<T>(path, formData);
  47. }
  48. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  49. export async function apiDelete<T>(path: string, params: any & ParamWithCsrfKey = {}): Promise<T> {
  50. if (params._csrf == null) {
  51. params._csrf = csrfToken;
  52. }
  53. return apiRequest<T>('delete', path, { data: params });
  54. }