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