request.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { getUserId } from '@/utils';
  2. import { message } from 'antd';
  3. import { isPlainObject } from 'lodash';
  4. import axios from './ctx-axios';
  5. const DEFAULT_HEADERS = {
  6. 'content-type': 'application/json',
  7. 'User-Id': getUserId(),
  8. };
  9. // body 字段 trim
  10. const sanitizeBody = (obj: Record<string, any>): string => {
  11. // simple shallow copy to avoid changing original obj
  12. if (!isPlainObject(obj)) return JSON.stringify(obj);
  13. const resObj = { ...obj };
  14. for (const key in resObj) {
  15. const val = resObj[key];
  16. if (typeof val === 'string') {
  17. resObj[key] = val.trim();
  18. }
  19. }
  20. return JSON.stringify(resObj);
  21. };
  22. export const sendGetRequest = (url: string, qs?: { [key: string]: any }) => {
  23. if (qs) {
  24. const str = Object.keys(qs)
  25. .filter(k => qs[k] !== undefined && qs[k] !== '')
  26. .map(k => `${k}=${qs[k]}`)
  27. .join('&');
  28. if (str) {
  29. url += `?${str}`;
  30. }
  31. }
  32. return axios
  33. .get<null, any>('/api' + url, {
  34. headers: DEFAULT_HEADERS,
  35. })
  36. .then(res => res)
  37. .catch(err => {
  38. message.error(err);
  39. Promise.reject(err);
  40. });
  41. };
  42. export const sendSpaceGetRequest = (url: string, qs?: { [key: string]: any }) => {
  43. if (qs) {
  44. const str = Object.keys(qs)
  45. .filter(k => qs[k] !== undefined && qs[k] !== '')
  46. .map(k => `${k}=${qs[k]}`)
  47. .join('&');
  48. if (str) {
  49. url += `?${str}`;
  50. }
  51. }
  52. return axios
  53. .get<null, any>(url, {
  54. headers: DEFAULT_HEADERS,
  55. })
  56. .then(res => res)
  57. .catch(err => {
  58. message.error(err);
  59. Promise.reject(err);
  60. });
  61. };
  62. export const sendPostRequest = (url: string, body?: any) => {
  63. const reqBody = sanitizeBody(body);
  64. return axios
  65. .post<null, any>('/api' + url, {
  66. body: reqBody,
  67. headers: DEFAULT_HEADERS,
  68. })
  69. .then(res => res)
  70. .catch(err => {
  71. message.error(err);
  72. Promise.reject(err);
  73. });
  74. };
  75. export const sendSpacePostRequest = (url: string, body?: any) => {
  76. return axios
  77. .post<null, any>(url, body, {
  78. headers: DEFAULT_HEADERS,
  79. })
  80. .then(res => res)
  81. .catch(err => {
  82. message.error(err);
  83. Promise.reject(err);
  84. });
  85. };
  86. export const sendSpaceUploadPostRequest = (url: string, body?: any) => {
  87. return axios
  88. .post<null, any>(url, body)
  89. .then(res => res)
  90. .catch(err => {
  91. message.error(err);
  92. Promise.reject(err);
  93. });
  94. };