app.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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, {
  17. extraRouteArr,
  18. getMenuPathByCode,
  19. getMenus,
  20. handleRoutes,
  21. saveMenusCache,
  22. } from '@/utils/menu';
  23. import { AIcon } from '@/components';
  24. import React from 'react';
  25. import 'moment/dist/locale/zh-cn';
  26. import moment from 'moment';
  27. moment.locale('zh-cn');
  28. const isDev = process.env.NODE_ENV === 'development';
  29. const loginPath = '/user/login';
  30. const bindPath = '/account/center/bind';
  31. let extraRoutes: any[] = [];
  32. /** 获取用户信息比较慢的时候会展示一个 loading */
  33. export const initialStateConfig = {
  34. loading: <PageLoading />,
  35. };
  36. /**
  37. * @see https://umijs.org/zh-CN/plugins/plugin-initial-state
  38. * */
  39. export async function getInitialState(): Promise<{
  40. settings?: Partial<LayoutSettings>;
  41. currentUser?: UserInfo;
  42. fetchUserInfo?: () => Promise<UserInfo | undefined>;
  43. }> {
  44. const fetchUserInfo = async () => {
  45. try {
  46. const user = await Service.queryCurrent();
  47. const detail = await Service.userDetail();
  48. // console.log(user.result,'user')
  49. return {
  50. ...user.result,
  51. user: {
  52. ...user.result.user,
  53. avatar: detail.result.avatar,
  54. },
  55. };
  56. } catch (error) {
  57. history.push(loginPath);
  58. }
  59. return undefined;
  60. };
  61. const getSettings = async () => {
  62. try {
  63. const res = await Service.settingDetail('basis');
  64. return res.result;
  65. } catch (error) {
  66. history.push(loginPath);
  67. }
  68. return undefined;
  69. };
  70. // 如果是登录页面,不执行
  71. if (history.location.pathname !== loginPath && history.location.pathname !== bindPath) {
  72. const currentUser = await fetchUserInfo();
  73. const settings = await getSettings();
  74. return {
  75. fetchUserInfo,
  76. currentUser,
  77. settings: settings,
  78. };
  79. }
  80. // 链接websocket
  81. const url = `${document.location.protocol.replace('http', 'ws')}//${document.location.host}/${
  82. SystemConst.API_BASE
  83. }/messaging/${Token.get()}?:X_Access_Token=${Token.get()}`;
  84. const ws = new ReconnectingWebSocket(url);
  85. // ws.send('sss');
  86. ws.onerror = () => {
  87. console.log('链接错误。ws');
  88. };
  89. return {
  90. fetchUserInfo,
  91. settings: {},
  92. };
  93. }
  94. /**
  95. * 异常处理程序
  96. 200: '服务器成功返回请求的数据。',
  97. 201: '新建或修改数据成功。',
  98. 202: '一个请求已经进入后台排队(异步任务)。',
  99. 204: '删除数据成功。',
  100. 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  101. 401: '用户没有权限(令牌、用户名、密码错误)。',
  102. 403: '用户得到授权,但是访问是被禁止的。',
  103. 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  104. 405: '请求方法不被允许。',
  105. 406: '请求的格式不可得。',
  106. 410: '请求的资源被永久删除,且不会再得到的。',
  107. 422: '当创建一个对象时,发生一个验证错误。',
  108. 500: '服务器发生错误,请检查服务器。',
  109. 502: '网关错误。',
  110. 503: '服务不可用,服务器暂时过载或维护。',
  111. 504: '网关超时。',
  112. //-----English
  113. 200: The server successfully returned the requested data. ',
  114. 201: New or modified data is successful. ',
  115. 202: A request has entered the background queue (asynchronous task). ',
  116. 204: Data deleted successfully. ',
  117. 400: 'There was an error in the request sent, and the server did not create or modify data. ',
  118. 401: The user does not have permission (token, username, password error). ',
  119. 403: The user is authorized, but access is forbidden. ',
  120. 404: The request sent was for a record that did not exist. ',
  121. 405: The request method is not allowed. ',
  122. 406: The requested format is not available. ',
  123. 410':
  124. 'The requested resource is permanently deleted and will no longer be available. ',
  125. 422: When creating an object, a validation error occurred. ',
  126. 500: An error occurred on the server, please check the server. ',
  127. 502: Gateway error. ',
  128. 503: The service is unavailable. ',
  129. 504: The gateway timed out. ',
  130. * @see https://beta-pro.ant.design/docs/request-cn
  131. */
  132. /**
  133. * Token 拦截器
  134. * @param url
  135. * @param options
  136. */
  137. const filterUrl = [
  138. '/authorize/captcha/config',
  139. '/authorize/login',
  140. '/sso/bind-code/',
  141. '/sso/providers',
  142. ];
  143. const requestInterceptor = (url: string, options: RequestOptionsInit) => {
  144. // const {params} = options;
  145. let authHeader = {};
  146. if (!filterUrl.some((fUrl) => url.includes(fUrl))) {
  147. authHeader = { 'X-Access-Token': Token.get() || '' };
  148. }
  149. return {
  150. url: `${url}`,
  151. options: {
  152. ...options,
  153. // 格式化成后台需要的查询参数
  154. // params: encodeQueryParam(params),
  155. interceptors: true,
  156. headers: authHeader,
  157. },
  158. };
  159. };
  160. export const request: RequestConfig = {
  161. errorHandler: (error: any) => {
  162. const { response } = error;
  163. if (response.status === 401) {
  164. history.push('/user/login');
  165. return;
  166. }
  167. if (
  168. response.status === 400 ||
  169. response.status === 500 ||
  170. response.status === 404 ||
  171. response.status === 403
  172. ) {
  173. // 添加clone() 避免后续其它地方用response.text()时报错
  174. response
  175. .clone()
  176. .text()
  177. .then((resp: string) => {
  178. if (resp) {
  179. notification.error({
  180. key: 'error',
  181. message: JSON.parse(resp || '{}').message || '服务器内部错误!',
  182. });
  183. } else {
  184. response
  185. .clone()
  186. .json()
  187. .then((res: any) => {
  188. notification.error({
  189. key: 'error',
  190. message: `请求错误:${res.message}`,
  191. });
  192. })
  193. .catch(() => {
  194. notification.error({
  195. key: 'error',
  196. message: '系统开小差,请稍后重试',
  197. });
  198. });
  199. }
  200. });
  201. return response;
  202. }
  203. if (!response) {
  204. notification.error({
  205. description: '网络异常,请检查网络连接',
  206. message: '网络异常',
  207. });
  208. }
  209. return response;
  210. },
  211. requestInterceptors: [requestInterceptor],
  212. };
  213. const MenuItemIcon = (
  214. menuItemProps: any,
  215. defaultDom: React.ReactNode,
  216. props: any,
  217. ): React.ReactNode => {
  218. if (defaultDom) {
  219. // @ts-ignore
  220. const menuItem = React.cloneElement(defaultDom, {
  221. // @ts-ignore
  222. children: [<AIcon type={menuItemProps.icon as string} />, defaultDom.props.children[1]],
  223. ...props,
  224. });
  225. return menuItem;
  226. }
  227. return defaultDom;
  228. };
  229. // ProLayout 支持的api https://procomponents.ant.design/components/layout
  230. export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  231. // console.log({ ...initialState });
  232. const ico: any = document.querySelector('link[rel="icon"]');
  233. if (ico !== null) {
  234. Service.settingDetail('basis').then((res) => {
  235. if (res.status === 200) {
  236. // console.log(res.result.ico)
  237. ico.href = res.result.ico;
  238. }
  239. });
  240. }
  241. return {
  242. navTheme: 'light',
  243. headerTheme: 'light',
  244. rightContentRender: () => <RightContent />,
  245. disableContentMargin: false,
  246. waterMarkProps: {
  247. // content: initialState?.currentUser?.name,
  248. },
  249. itemRender: (route, _, routes) => {
  250. const isToParentUrl = getMenuPathByCode('notice');
  251. const chilck = routes.indexOf(route) !== 0;
  252. const goto = routes.some((item) => {
  253. if (!route.path.includes('iot')) {
  254. return routes.indexOf(route) <= 1;
  255. } else {
  256. if (route.path.includes('notice')) {
  257. return item.path.indexOf(isToParentUrl) > -1;
  258. } else {
  259. return routes.indexOf(route) > 1;
  260. }
  261. }
  262. });
  263. return chilck && goto && route.path !== '/iot/link/Channel' ? (
  264. <Link to={route.path}>{route.breadcrumbName}</Link>
  265. ) : (
  266. <span>{route.breadcrumbName}</span>
  267. );
  268. },
  269. footerRender: () => <Footer />,
  270. onPageChange: () => {
  271. const { location } = history;
  272. // 如果没有登录,重定向到 login
  273. if (
  274. !initialState?.currentUser &&
  275. location.pathname !== loginPath &&
  276. location.pathname !== bindPath
  277. ) {
  278. history.push(loginPath);
  279. }
  280. },
  281. menuDataRender: () => {
  282. return getMenus(extraRoutes);
  283. },
  284. subMenuItemRender: MenuItemIcon,
  285. menuItemRender: (menuItemProps, defaultDom) => {
  286. return MenuItemIcon(menuItemProps, defaultDom, {
  287. onClick: () => {
  288. history.push(menuItemProps.path!);
  289. },
  290. });
  291. },
  292. links: isDev
  293. ? [
  294. <Link key={1} to="/umi/plugin/openapi" target="_blank">
  295. <LinkOutlined />
  296. <span>OpenAPI 文档</span>
  297. </Link>,
  298. <Link key={2} to="/~docs">
  299. <BookOutlined />
  300. <span>业务组件文档</span>
  301. </Link>,
  302. ]
  303. : [],
  304. menuHeaderRender: undefined,
  305. // 自定义 403 页面
  306. // unAccessible: <div>unAccessible</div>,
  307. ...initialState?.settings,
  308. // title: '',
  309. // logo:''
  310. };
  311. };
  312. export function patchRoutes(routes: any) {
  313. if (extraRoutes && extraRoutes.length) {
  314. const basePath = routes.routes.find((_route: any) => _route.path === '/')!;
  315. const _routes = getRoutes(extraRoutes);
  316. const baseRedirect = {
  317. path: '/',
  318. routes: [
  319. ..._routes,
  320. {
  321. path: '/',
  322. redirect: _routes[0].path,
  323. },
  324. ],
  325. };
  326. basePath.routes = [...basePath.routes, baseRedirect];
  327. console.log(basePath.routes);
  328. }
  329. }
  330. export function render(oldRender: any) {
  331. if (history.location.pathname !== loginPath && history.location.pathname !== bindPath) {
  332. // SystemConfigService.getAMapKey().then((res) => {
  333. // if (res && res.status === 200 && res.result) {
  334. // localStorage.setItem(SystemConst.AMAP_KEY, res.result.apiKey);
  335. // }
  336. // });
  337. Service.settingDetail('api').then((res) => {
  338. if (res && res.status === 200 && res.result) {
  339. localStorage.setItem(SystemConst.AMAP_KEY, res.result.api);
  340. }
  341. });
  342. MenuService.queryOwnThree({ paging: false }).then((res) => {
  343. if (res && res.status === 200) {
  344. if (isDev) {
  345. res.result.push({
  346. code: 'demo',
  347. id: 'demo',
  348. name: '例子',
  349. url: '/demo',
  350. });
  351. }
  352. extraRoutes = handleRoutes([...res.result, ...extraRouteArr]);
  353. saveMenusCache(extraRoutes);
  354. }
  355. oldRender();
  356. });
  357. } else {
  358. oldRender();
  359. }
  360. }