create.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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['patientId'] = '783';
  24. header['doctorId'] = wx.getStorageSync('doctorId') ?? '';
  25. header['appId'] = miniProgram.appId ?? '';
  26. header['version'] = miniProgram.version ?? '';
  27. header['env'] = miniProgram.envVersion ?? '';
  28. const promise = _request<IRequestData<T>>({
  29. url: /https?\:\/\//.test(url) ? url : `${baseURL}${url}`,
  30. header, data, ..._config,
  31. }).then(response => {
  32. if (response.statusCode === 200) {
  33. if (response.data.code === 200 && response.data.success !== false) {
  34. const data = Array.isArray(response.data.rows) && response.data.total != null
  35. ? { data: response.data.rows, total: response.data.total }
  36. : response.data.data
  37. return transform({ data: data as any, header: response.header });
  38. }
  39. throw { errMsg: response.data.msg || `app:${response.data.code}`, errno: `060202${response.data.code}` }
  40. }
  41. throw { errMsg: `${response.errMsg}:${response.statusCode}`, errno: `060201${response.statusCode}` }
  42. });
  43. if (shareRequest) shareRequestCache.set(key, <any>promise);
  44. return (promise as any).catch(async (error: { errno: string }) => {
  45. shareRequestCache.delete(key);
  46. if (error.errno === '060201401') {
  47. await login(true, '重新登录中');
  48. wx.showLoading({ title: '重新加载中', });
  49. try {
  50. return await request(config);
  51. } catch (error) {
  52. throw error;
  53. } finally {
  54. wx.hideLoading();
  55. }
  56. }
  57. throw error;
  58. });
  59. }
  60. }