request.ts 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. export type Method =
  2. | 'get'
  3. | 'GET'
  4. | 'delete'
  5. | 'DELETE'
  6. | 'head'
  7. | 'HEAD'
  8. | 'options'
  9. | 'OPTIONS'
  10. | 'post'
  11. | 'POST'
  12. | 'put'
  13. | 'PUT'
  14. | 'patch'
  15. | 'PATCH';
  16. /**
  17. * Parse route parameters for responseType
  18. */
  19. const reg = /:[a-z|A-Z]+/g;
  20. export function parseParams(url: string): Array<string> {
  21. const ps = url.match(reg);
  22. if (!ps) {
  23. return [];
  24. }
  25. return ps.map((k) => k.replace(/:/, ''));
  26. }
  27. /**
  28. * Generate url and parameters
  29. * @param url
  30. * @param params
  31. */
  32. export function genUrl(url: string, params: unknown) {
  33. if (!params) {
  34. return url;
  35. }
  36. const ps = parseParams(url);
  37. ps.forEach((k) => {
  38. const reg = new RegExp(`:${k}`);
  39. url = url.replace(reg, params[k]);
  40. });
  41. const path: Array<string> = [];
  42. for (const key of Object.keys(params)) {
  43. if (!ps.find((k) => k === key)) {
  44. path.push(`${key}=${params[key]}`);
  45. }
  46. }
  47. return url + (path.length > 0 ? `?${path.join('&')}` : '');
  48. }
  49. export async function request({
  50. method,
  51. url,
  52. data,
  53. config = {}
  54. }: {
  55. method: Method;
  56. url: string;
  57. data?: unknown;
  58. config?: unknown;
  59. }) {
  60. const response = await fetch(url, {
  61. method: method.toLocaleUpperCase(),
  62. credentials: 'include',
  63. headers: {
  64. 'Content-Type': 'application/json'
  65. },
  66. body: data ? JSON.stringify(data) : undefined,
  67. // @ts-ignore
  68. ...config
  69. });
  70. return response.json();
  71. }
  72. function api<T>(
  73. method: Method = 'get',
  74. url: string,
  75. req: any,
  76. config?: unknown
  77. ): Promise<T> {
  78. if (url.match(/:/) || method.match(/get|delete/i)) {
  79. url = genUrl(url, req.params || req.forms);
  80. }
  81. method = method.toLocaleLowerCase() as Method;
  82. switch (method) {
  83. case 'get':
  84. return request({method: 'get', url, data: req, config});
  85. case 'delete':
  86. return request({method: 'delete', url, data: req, config});
  87. case 'put':
  88. return request({method: 'put', url, data: req, config});
  89. case 'post':
  90. return request({method: 'post', url, data: req, config});
  91. case 'patch':
  92. return request({method: 'patch', url, data: req, config});
  93. default:
  94. return request({method: 'post', url, data: req, config});
  95. }
  96. }
  97. export const webapi = {
  98. get<T>(url: string, req: unknown, config?: unknown): Promise<T> {
  99. return api<T>('get', url, req, config);
  100. },
  101. delete<T>(url: string, req: unknown, config?: unknown): Promise<T> {
  102. return api<T>('delete', url, req, config);
  103. },
  104. put<T>(url: string, req: unknown, config?: unknown): Promise<T> {
  105. return api<T>('get', url, req, config);
  106. },
  107. post<T>(url: string, req: unknown, config?: unknown): Promise<T> {
  108. return api<T>('post', url, req, config);
  109. },
  110. patch<T>(url: string, req: unknown, config?: unknown): Promise<T> {
  111. return api<T>('patch', url, req, config);
  112. }
  113. };
  114. export default webapi