flowservice.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import Vue from 'vue'
  2. const methods = [
  3. 'sessionNew', 'sessionLoad', // SESSION
  4. 'documentUpdate', 'documentRun', 'documentSave', // DOCUMENT
  5. 'chatEvent', 'chatJoin', 'chatRename', // CHAT
  6. 'linkAdd', 'linkUpdate', 'linkRemove', // LINK
  7. 'triggerAdd', 'triggerUpdate', 'triggerRemove',
  8. 'nodeUpdate', 'nodeAdd', 'nodeRemove', 'nodeProcess' // NODE
  9. ]
  10. const debug = 0
  11. // FlowWSService
  12. let log = () => {}
  13. if (debug) {
  14. log = console.log.bind(console.log, '%cSVC:', 'color:#0a0', (Math.random() * 1000).toFixed())
  15. }
  16. function FlowService () {
  17. // singleton per module
  18. var ws = null
  19. var connected = false
  20. var reconnect = false
  21. var eventBus = new Vue()
  22. var loc = '' // The location
  23. // WS Connector
  24. function connect () {
  25. reconnect = true
  26. ws = new window.WebSocket(loc)
  27. ws.onopen = () => {
  28. log('connected', ws)
  29. connected = true
  30. eventBus.$emit('open')
  31. }
  32. ws.onmessage = (e) => { // receiving message
  33. log('received:', e.data)
  34. const msg = JSON.parse(e.data)
  35. eventBus.$emit(msg.op, msg) // Pass message through
  36. }
  37. ws.onerror = (e) => { connected = false }
  38. ws.onclose = (e) => {
  39. log('Lost connection', e)
  40. if (connected === true) {
  41. eventBus.$emit('close')
  42. } // emit close
  43. connected = false
  44. if (reconnect !== true) {
  45. return
  46. }
  47. setTimeout(() => connect(loc), 3000) // Reconnect
  48. }
  49. }
  50. const service = {
  51. send (msg) {
  52. ws.send(JSON.stringify(msg))
  53. },
  54. connected (cb) {
  55. if (connected === false) {
  56. eventBus.$on('open', cb)
  57. return
  58. }
  59. cb()
  60. },
  61. on: eventBus.$on.bind(eventBus),
  62. once: eventBus.$once.bind(eventBus),
  63. off: eventBus.$off.bind(eventBus),
  64. connect (ploc) {
  65. loc = ploc
  66. if (ws) { ws.close() }
  67. if (!reconnect) connect()
  68. log('Connecting to', loc)
  69. },
  70. close () {
  71. if (!ws) { return }
  72. ws.close()
  73. }
  74. }
  75. methods.forEach(ftyp => {
  76. service[ftyp] = (param, id) => {
  77. log('sending:', ftyp, ' -- ', param)
  78. if (connected) {
  79. service.send({op: ftyp, id: id, data: param})
  80. return
  81. }
  82. if (ftyp !== 'documentUpdate') return // Do not persist other than documentUpdate on reconnection
  83. // Schedule when is connected
  84. const lparam = JSON.parse(JSON.stringify(param))
  85. service.once('open', () => {
  86. console.log('Sending the persistend: ', ftyp)
  87. service.send({op: ftyp, id: id, data: lparam})
  88. })
  89. }
  90. })
  91. Object.assign(this, service)
  92. }
  93. export default new FlowService()