app.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. return {
  233. navTheme: 'light',
  234. headerTheme: 'light',
  235. rightContentRender: () => <RightContent />,
  236. disableContentMargin: false,
  237. waterMarkProps: {
  238. // content: initialState?.currentUser?.name,
  239. },
  240. itemRender: (route, _, routes) => {
  241. const isToParentUrl = getMenuPathByCode('notice');
  242. const chilck = routes.indexOf(route) !== 0;
  243. const goto = routes.some((item) => {
  244. if (!route.path.includes('iot')) {
  245. return routes.indexOf(route) <= 1;
  246. } else {
  247. if (route.path.includes('notice')) {
  248. return item.path.indexOf(isToParentUrl) > -1;
  249. } else {
  250. return routes.indexOf(route) > 1;
  251. }
  252. }
  253. });
  254. return chilck && goto && route.path !== '/iot/link/Channel' ? (
  255. <Link to={route.path}>{route.breadcrumbName}</Link>
  256. ) : (
  257. <span>{route.breadcrumbName}</span>
  258. );
  259. },
  260. footerRender: () => <Footer />,
  261. onPageChange: () => {
  262. const { location } = history;
  263. // 如果没有登录,重定向到 login
  264. if (
  265. !initialState?.currentUser &&
  266. location.pathname !== loginPath &&
  267. location.pathname !== bindPath
  268. ) {
  269. history.push(loginPath);
  270. }
  271. },
  272. menuDataRender: () => {
  273. return getMenus(extraRoutes);
  274. },
  275. subMenuItemRender: MenuItemIcon,
  276. menuItemRender: (menuItemProps, defaultDom) => {
  277. return MenuItemIcon(menuItemProps, defaultDom, {
  278. onClick: () => {
  279. history.push(menuItemProps.path!);
  280. },
  281. });
  282. },
  283. links: isDev
  284. ? [
  285. <Link key={1} to="/umi/plugin/openapi" target="_blank">
  286. <LinkOutlined />
  287. <span>OpenAPI 文档</span>
  288. </Link>,
  289. <Link key={2} to="/~docs">
  290. <BookOutlined />
  291. <span>业务组件文档</span>
  292. </Link>,
  293. ]
  294. : [],
  295. menuHeaderRender: undefined,
  296. // 自定义 403 页面
  297. // unAccessible: <div>unAccessible</div>,
  298. ...initialState?.settings,
  299. // title: '',
  300. // logo:''
  301. };
  302. };
  303. export function patchRoutes(routes: any) {
  304. if (extraRoutes && extraRoutes.length) {
  305. const basePath = routes.routes.find((_route: any) => _route.path === '/')!;
  306. const _routes = getRoutes(extraRoutes);
  307. const baseRedirect = {
  308. path: '/',
  309. routes: [
  310. ..._routes,
  311. {
  312. path: '/',
  313. redirect: _routes[0].path,
  314. },
  315. ],
  316. };
  317. basePath.routes = [...basePath.routes, baseRedirect];
  318. console.log(basePath.routes);
  319. }
  320. }
  321. export function render(oldRender: any) {
  322. if (history.location.pathname !== loginPath && history.location.pathname !== bindPath) {
  323. // SystemConfigService.getAMapKey().then((res) => {
  324. // if (res && res.status === 200 && res.result) {
  325. // localStorage.setItem(SystemConst.AMAP_KEY, res.result.apiKey);
  326. // }
  327. // });
  328. Service.settingDetail('api').then((res) => {
  329. if (res && res.status === 200 && res.result) {
  330. localStorage.setItem(SystemConst.AMAP_KEY, res.result.api);
  331. }
  332. });
  333. MenuService.queryOwnThree({ paging: false }).then((res) => {
  334. if (res && res.status === 200) {
  335. if (isDev) {
  336. res.result.push({
  337. code: 'demo',
  338. id: 'demo',
  339. name: '例子',
  340. url: '/demo',
  341. });
  342. }
  343. extraRoutes = handleRoutes([...res.result, ...extraRouteArr]);
  344. saveMenusCache(extraRoutes);
  345. }
  346. oldRender();
  347. });
  348. } else {
  349. oldRender();
  350. }
  351. }