Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1.  
  2. send(type, data = {}) {
  3. const httpRequest = () => axiosInstanse
  4. .post('/microservice/ask', { name: type, payload: data }, {
  5. headers: {
  6. Authorization: this.token,
  7. },
  8. }).then(r => r.data);
  9.  
  10. const socketRequest = () => {
  11. const request = {
  12. sendTime: Date.now(),
  13. msgid: Math.random().toString(36).substr(2, 8),
  14. type,
  15. data,
  16. };
  17. const promise = new Promise((resolve, reject) => {
  18. request.resolve = resolve;
  19. request.reject = reject;
  20. });
  21. this.requestMap[request.msgid] = request;
  22.  
  23. console.socket('>>> Server.send', type, request);
  24. this.socket.emit('d', request);
  25.  
  26. return promise;
  27. };
  28.  
  29. const cacheRequest = (cache) => {
  30. console.log(`load ${cache.headers.type} from cache`);
  31.  
  32. const response = JSON.parse(JSON.stringify({
  33. data: cache.body,
  34. }));
  35.  
  36. console.log(1, response);
  37. // window.globalVars = window.globalVars.filter(cacheItem => !CompareObjects(cacheItem, cache));
  38. return response;
  39. };
  40.  
  41. const findCache = (cacheType, cacheData) => {
  42. if (!window.globalVars || !Array.isArray(window.globalVars)) {
  43. return false;
  44. }
  45.  
  46.  
  47. const cache = window.globalVars.find(cacheItem => {
  48. console.log(type, JSON.stringify(cacheData), JSON.stringify(cacheItem.headers.data));
  49. return cacheItem.headers && cacheItem.headers.type === cacheType && CompareObjects(cacheItem.headers.data, cacheData)
  50. });
  51.  
  52. return cache || false;
  53. };
  54.  
  55. try {
  56. const cache = findCache(type, data);
  57. if (cache) return cacheRequest(cache);
  58. if (this.socket && this.getters.socketAlive) {
  59. if (WS_TO_HTTP_REDIRECTS[type]) return httpRequest();
  60. return socketRequest();
  61. }
  62. return httpRequest();
  63. } catch (e) {
  64. console.log(e);
  65. return httpRequest().then(r => { console.log(2, r); return r; });
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement