create.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { login } from "../logic";
  2. import { request as _request } from "../wx/network";
  3. const shareRequestCache = new Map<string, IRequestData<any>>();
  4. export function createRequest(option: IRequestCreateConfig) {
  5. const { baseURL } = option;
  6. return async function request<R, T>(config: IRequestConfig<R, T>) {
  7. let { url, data, params, header, meta, transform = (params: any) => params, shareRequest, ..._config } = config;
  8. if (config.method === 'GET') {
  9. data = params;
  10. } else if (params) {
  11. const query = Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
  12. url += `?${query.join('&')}`
  13. }
  14. const key = url;
  15. if (shareRequest && shareRequestCache.has(key)) {
  16. return shareRequestCache.get(key) as unknown as PromiseLike<IRequestData<T>>;
  17. }
  18. header ??= {};
  19. header['Authorization'] = meta?.ignoreToken ? '' : await option.token?.() ?? '';
  20. header['patientId'] = wx.getStorageSync('patientId') ?? '';
  21. header['doctorId'] = wx.getStorageSync('doctorId') ?? '';
  22. const promise = _request<IRequestData<T>>({
  23. url: /https?\:\/\//.test(url) ? url : `${baseURL}${url}`,
  24. header, data, ..._config,
  25. }).then(response => {
  26. if (response.statusCode === 200) {
  27. if (response.data.code === 200 && response.data.success !== false) {
  28. const data = Array.isArray(response.data.rows) && response.data.total != null
  29. ? { data: response.data.rows, total: response.data.total }
  30. : response.data.data
  31. return transform({ data: data as any, header: response.header });
  32. }
  33. throw { errMsg: response.data.msg || `app:${response.data.code}`, errno: `060202${response.data.code}` }
  34. }
  35. throw { errMsg: `${response.errMsg}:${response.statusCode}`, errno: `060201${response.statusCode}` }
  36. });
  37. if (shareRequest) shareRequestCache.set(key, <any>promise);
  38. return (promise as any).catch(async (error: { errno: string }) => {
  39. shareRequestCache.delete(key);
  40. if (error.errno === '060201401') {
  41. await login(true, '重新登录中');
  42. wx.showLoading({ title: '重新加载中', });
  43. try {
  44. return await request(config);
  45. } catch (error) {
  46. throw error;
  47. } finally {
  48. wx.hideLoading();
  49. }
  50. }
  51. throw error;
  52. });
  53. }
  54. }