create.ts 2.6 KB

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