_util.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Interface data format used to return a unified format
  2. import { ResultEnum } from '@/enums/httpEnum';
  3. export function resultSuccess<T = Recordable>(result: T, { message = 'ok' } = {}) {
  4. return {
  5. code: ResultEnum.SUCCESS,
  6. result,
  7. message,
  8. type: 'success',
  9. };
  10. }
  11. export function resultPageSuccess<T = any>(
  12. page: number,
  13. pageSize: number,
  14. list: T[],
  15. { message = 'ok' } = {},
  16. ) {
  17. const pageData = pagination(page, pageSize, list);
  18. return {
  19. ...resultSuccess({
  20. items: pageData,
  21. total: list.length,
  22. }),
  23. message,
  24. };
  25. }
  26. export function resultError(
  27. message = 'Request failed',
  28. { code = ResultEnum.ERROR, result = null } = {},
  29. ) {
  30. return {
  31. code,
  32. result,
  33. message,
  34. type: 'error',
  35. };
  36. }
  37. export function pagination<T = any>(pageNo: number, pageSize: number, array: T[]): T[] {
  38. const offset = (pageNo - 1) * Number(pageSize);
  39. return offset + Number(pageSize) >= array.length
  40. ? array.slice(offset, array.length)
  41. : array.slice(offset, offset + Number(pageSize));
  42. }
  43. export interface requestParams {
  44. method: string;
  45. body: any;
  46. headers?: { authorization?: string };
  47. query: any;
  48. }
  49. /**
  50. * @description 本函数用于从request数据中获取token,请根据项目的实际情况修改
  51. *
  52. */
  53. export function getRequestToken({ headers }: requestParams): string | undefined {
  54. return headers?.authorization;
  55. }