app.tsx 7.6 KB

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