app.tsx 9.9 KB

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