app.tsx 8.9 KB

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