apiv3-client.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import * as urljoin from 'url-join';
  2. // eslint-disable-next-line no-restricted-imports
  3. import { AxiosResponse } from 'axios';
  4. import loggerFactory from '~/utils/logger';
  5. import axios from '~/utils/axios';
  6. import { toArrayIfNot } from '~/utils/array-utils';
  7. const apiv3Root = '/_api/v3';
  8. const logger = loggerFactory('growi:apiv3');
  9. // get csrf token from body element
  10. const body = document.querySelector('body');
  11. const csrfToken = body?.dataset.csrftoken;
  12. type ParamWithCsrfKey = {
  13. _csrf: string,
  14. }
  15. const apiv3ErrorHandler = (_err) => {
  16. // extract api errors from general 400 err
  17. const err = _err.response ? _err.response.data.errors : _err;
  18. const errs = toArrayIfNot(err);
  19. for (const err of errs) {
  20. logger.error(err.message);
  21. }
  22. return errs;
  23. };
  24. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  25. export async function apiv3Request<T = any>(method: string, path: string, params: unknown): Promise<AxiosResponse<T>> {
  26. try {
  27. const res = await axios[method](urljoin(apiv3Root, path), params);
  28. return res.data;
  29. }
  30. catch (err) {
  31. const errors = apiv3ErrorHandler(err);
  32. throw errors;
  33. }
  34. }
  35. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  36. export async function apiv3Get<T = any>(path: string, params: unknown = {}): Promise<AxiosResponse<T>> {
  37. return apiv3Request('get', path, { params });
  38. }
  39. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  40. export async function apiv3Post<T = any>(path: string, params: any & ParamWithCsrfKey = {}): Promise<AxiosResponse<T>> {
  41. if (params._csrf == null) {
  42. params._csrf = csrfToken;
  43. }
  44. return apiv3Request('post', path, params);
  45. }
  46. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  47. export async function apiv3Put<T = any>(path: string, params: any & ParamWithCsrfKey = {}): Promise<AxiosResponse<T>> {
  48. if (params._csrf == null) {
  49. params._csrf = csrfToken;
  50. }
  51. return apiv3Request('put', path, params);
  52. }
  53. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  54. export async function apiv3Delete<T = any>(path: string, params: any & ParamWithCsrfKey = {}): Promise<AxiosResponse<T>> {
  55. if (params._csrf == null) {
  56. params._csrf = csrfToken;
  57. }
  58. return apiv3Request('delete', path, { params });
  59. }