Connection.js 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * 在 ajax request 前修改url,增加服务端`basePath`
  3. * `basePath`在`app.json`配置
  4. */
  5. Ext.define('saas.override.data.Connection', {
  6. override: 'Ext.data.Connection',
  7. urlRegexp: /(http|ftp|https):\/\//,
  8. config: {
  9. /**
  10. * @cfg {Object} defaultServerHeaders
  11. * 与defaultHeaders有区别,只在调用server api的时候才添加的headers
  12. */
  13. defaultServerHeaders: null
  14. },
  15. privates: {
  16. parseBasePath: function(basePath) {
  17. if (Ext.isObject(basePath)) {
  18. var protocol = window.location.protocol.split(":")[0];
  19. if (protocol === 'file') {
  20. protocol = 'https';
  21. }
  22. return basePath[protocol];
  23. }
  24. return basePath;
  25. },
  26. setupServerOptions: function(options) {
  27. var serverOptions = Ext.manifest.server, originUrl = options.url;
  28. if (serverOptions && serverOptions.basePath && !this.urlRegexp.test(originUrl) &&
  29. (!serverOptions.urlPattern || new RegExp(serverOptions.urlPattern).test(originUrl))) {
  30. Ext.Object.merge(options, {
  31. url: this.parseBasePath(serverOptions.basePath)
  32. + (originUrl.indexOf('/') == 0 ? '' : '/') + originUrl,
  33. headers: this.getDefaultServerHeaders() || {}
  34. });
  35. }
  36. }
  37. },
  38. request: function(options) {
  39. if (options && options.url) {
  40. this.setupServerOptions(options);
  41. }
  42. return this.callParent([options]);
  43. },
  44. onRequestComplete: function(request) {
  45. let headers = request.result.getAllResponseHeaders() || {},
  46. Authorization = headers['authorization'],
  47. result = request.result,
  48. res;
  49. try{
  50. res = JSON.parse(result.responseText);
  51. }catch(e) {
  52. res = result.responseJson
  53. // console.error(e);
  54. }
  55. if(res && res.code == 40001) {
  56. // 如果token超时则显示重新登陆弹窗
  57. saas.util.BaseUtil.showLoginWin();
  58. throw new Error('回话已过期');
  59. }
  60. if(Authorization) {
  61. // 如果返回了token则刷新token
  62. let headers = Ext.Ajax.getDefaultHeaders() || {};
  63. let session = saas.util.State.get('session');
  64. headers['Authorization'] = Authorization;
  65. Ext.Ajax.setDefaultHeaders(headers);
  66. session.token = Authorization;
  67. session.timestamp = Ext.now();
  68. saas.util.State.set('session', session);
  69. let sessionStr = session ? JSON.stringify(session) : '';
  70. if (typeof require === 'function') {
  71. let ipc = require('electron').ipcRenderer;
  72. ipc.send('session.change', sessionStr);
  73. }else {
  74. //解析session 把data作为sessionStr
  75. sessionStr = session ? JSON.stringify(session.data) : '';
  76. const frame = window.frames[window.frames.length - 1];
  77. frame.postMessage(sessionStr, '*');
  78. }
  79. }
  80. },
  81. });