app.tsx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
  2. import { PageLoading } from '@ant-design/pro-layout';
  3. import { notification } from 'antd';
  4. import type { RequestConfig, RunTimeLayoutConfig } from 'umi';
  5. import { history, Link } from 'umi';
  6. import RightContent from '@/components/RightContent';
  7. import Footer from '@/components/Footer';
  8. import { BookOutlined, LinkOutlined } from '@ant-design/icons';
  9. import Service from '@/pages/user/Login/service';
  10. import Token from '@/utils/token';
  11. import type { RequestOptionsInit } from 'umi-request';
  12. import ReconnectingWebSocket from 'reconnecting-websocket';
  13. import SystemConst from '@/utils/const';
  14. import { service as MenuService } from '@/pages/system/Menu';
  15. import getRoutes, { getMenus, handleRoutes, saveMenusCache } from '@/utils/menu';
  16. import { AIcon } from '@/components';
  17. const isDev = process.env.NODE_ENV === 'development';
  18. const loginPath = '/user/login';
  19. let extraRoutes: any[] = [];
  20. /** 获取用户信息比较慢的时候会展示一个 loading */
  21. export const initialStateConfig = {
  22. loading: <PageLoading />,
  23. };
  24. /**
  25. * @see https://umijs.org/zh-CN/plugins/plugin-initial-state
  26. * */
  27. export async function getInitialState(): Promise<{
  28. settings?: Partial<LayoutSettings>;
  29. currentUser?: UserInfo;
  30. fetchUserInfo?: () => Promise<UserInfo | undefined>;
  31. }> {
  32. const fetchUserInfo = async () => {
  33. try {
  34. const user = await Service.queryCurrent();
  35. return user.result;
  36. } catch (error) {
  37. history.push(loginPath);
  38. }
  39. return undefined;
  40. };
  41. // 如果是登录页面,不执行
  42. if (history.location.pathname !== loginPath) {
  43. const currentUser = await fetchUserInfo();
  44. return {
  45. fetchUserInfo,
  46. currentUser,
  47. settings: {},
  48. };
  49. }
  50. // 链接websocket
  51. const url = `${document.location.protocol.replace('http', 'ws')}//${document.location.host}/${
  52. SystemConst.API_BASE
  53. }/messaging/${Token.get()}?:X_Access_Token=${Token.get()}`;
  54. const ws = new ReconnectingWebSocket(url);
  55. // ws.send('sss');
  56. ws.onerror = () => {
  57. console.log('链接错误。ws');
  58. };
  59. return {
  60. fetchUserInfo,
  61. settings: {},
  62. };
  63. }
  64. /**
  65. * 异常处理程序
  66. 200: '服务器成功返回请求的数据。',
  67. 201: '新建或修改数据成功。',
  68. 202: '一个请求已经进入后台排队(异步任务)。',
  69. 204: '删除数据成功。',
  70. 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  71. 401: '用户没有权限(令牌、用户名、密码错误)。',
  72. 403: '用户得到授权,但是访问是被禁止的。',
  73. 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  74. 405: '请求方法不被允许。',
  75. 406: '请求的格式不可得。',
  76. 410: '请求的资源被永久删除,且不会再得到的。',
  77. 422: '当创建一个对象时,发生一个验证错误。',
  78. 500: '服务器发生错误,请检查服务器。',
  79. 502: '网关错误。',
  80. 503: '服务不可用,服务器暂时过载或维护。',
  81. 504: '网关超时。',
  82. //-----English
  83. 200: The server successfully returned the requested data. ',
  84. 201: New or modified data is successful. ',
  85. 202: A request has entered the background queue (asynchronous task). ',
  86. 204: Data deleted successfully. ',
  87. 400: 'There was an error in the request sent, and the server did not create or modify data. ',
  88. 401: The user does not have permission (token, username, password error). ',
  89. 403: The user is authorized, but access is forbidden. ',
  90. 404: The request sent was for a record that did not exist. ',
  91. 405: The request method is not allowed. ',
  92. 406: The requested format is not available. ',
  93. 410':
  94. 'The requested resource is permanently deleted and will no longer be available. ',
  95. 422: When creating an object, a validation error occurred. ',
  96. 500: An error occurred on the server, please check the server. ',
  97. 502: Gateway error. ',
  98. 503: The service is unavailable. ',
  99. 504: The gateway timed out. ',
  100. * @see https://beta-pro.ant.design/docs/request-cn
  101. */
  102. /**
  103. * Token 拦截器
  104. * @param url
  105. * @param options
  106. */
  107. const filterUrl = ['/authorize/captcha/config', '/authorize/login'];
  108. const requestInterceptor = (url: string, options: RequestOptionsInit) => {
  109. // const {params} = options;
  110. let authHeader = {};
  111. if (!filterUrl.some((fUrl) => url.includes(fUrl))) {
  112. authHeader = { 'X-Access-Token': Token.get() || '' };
  113. }
  114. return {
  115. url: `${url}`,
  116. options: {
  117. ...options,
  118. // 格式化成后台需要的查询参数
  119. // params: encodeQueryParam(params),
  120. interceptors: true,
  121. headers: authHeader,
  122. },
  123. };
  124. };
  125. export const request: RequestConfig = {
  126. errorHandler: (error: any) => {
  127. const { response } = error;
  128. if (response.status === 401) {
  129. history.push('/user/login');
  130. return;
  131. }
  132. if (response.status === 400 || response.status === 500) {
  133. response.text().then((resp: string) => {
  134. if (resp) {
  135. notification.error({
  136. key: 'error',
  137. message: JSON.parse(resp).message || '服务器内部错误!',
  138. });
  139. } else {
  140. response
  141. .json()
  142. .then((res: any) => {
  143. notification.error({
  144. key: 'error',
  145. message: `请求错误:${res.message}`,
  146. });
  147. })
  148. .catch(() => {
  149. notification.error({
  150. key: 'error',
  151. message: '系统错误',
  152. });
  153. });
  154. }
  155. });
  156. return response;
  157. }
  158. if (!response) {
  159. notification.error({
  160. description: '您的网络发生异常,无法连接服务器',
  161. message: '网络异常',
  162. });
  163. }
  164. return response;
  165. },
  166. requestInterceptors: [requestInterceptor],
  167. };
  168. // ProLayout 支持的api https://procomponents.ant.design/components/layout
  169. export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  170. return {
  171. navTheme: 'light',
  172. headerTheme: 'light',
  173. rightContentRender: () => <RightContent />,
  174. disableContentMargin: false,
  175. waterMarkProps: {
  176. // content: initialState?.currentUser?.name,
  177. },
  178. footerRender: () => <Footer />,
  179. onPageChange: () => {
  180. const { location } = history;
  181. // 如果没有登录,重定向到 login
  182. if (!initialState?.currentUser && location.pathname !== loginPath) {
  183. history.push(loginPath);
  184. }
  185. },
  186. menuDataRender: () => {
  187. return getMenus(extraRoutes);
  188. },
  189. menuItemRender: (menuItemProps) => {
  190. return (
  191. <Link to={menuItemProps.path}>
  192. <span className={`antd-pro-menu-item`}>
  193. {menuItemProps.icon && <AIcon type={menuItemProps.icon as string} />}
  194. <span className={`antd-pro-menu-item-title`}>{menuItemProps.name}</span>
  195. </span>
  196. </Link>
  197. );
  198. },
  199. links: isDev
  200. ? [
  201. <Link key={1} to="/umi/plugin/openapi" target="_blank">
  202. <LinkOutlined />
  203. <span>OpenAPI 文档</span>
  204. </Link>,
  205. <Link key={2} to="/~docs">
  206. <BookOutlined />
  207. <span>业务组件文档</span>
  208. </Link>,
  209. ]
  210. : [],
  211. menuHeaderRender: undefined,
  212. // 自定义 403 页面
  213. // unAccessible: <div>unAccessible</div>,
  214. ...initialState?.settings,
  215. title: '',
  216. };
  217. };
  218. export function patchRoutes(routes: any) {
  219. if (extraRoutes && extraRoutes.length) {
  220. const basePath = routes.routes.find((_route: any) => _route.path === '/')!;
  221. const _routes = getRoutes(extraRoutes);
  222. const baseRedirect = {
  223. path: '/',
  224. routes: [
  225. ..._routes,
  226. {
  227. path: '/',
  228. redirect: _routes[0].path,
  229. },
  230. ],
  231. };
  232. basePath.routes = [...basePath.routes, baseRedirect];
  233. console.log(basePath.routes);
  234. }
  235. }
  236. export function render(oldRender: any) {
  237. if (history.location.pathname !== loginPath) {
  238. MenuService.queryOwnThree({ paging: false }).then((res) => {
  239. if (res && res.status === 200) {
  240. extraRoutes = handleRoutes(res.result);
  241. saveMenusCache(extraRoutes);
  242. }
  243. oldRender();
  244. });
  245. } else {
  246. oldRender();
  247. }
  248. }