app.tsx 8.5 KB

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