UppySocket.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const ee = require('namespace-emitter')
  2. module.exports = class UppySocket {
  3. constructor (opts) {
  4. this.queued = []
  5. this.isOpen = false
  6. this.socket = new WebSocket(opts.target)
  7. this.emitter = ee()
  8. this.socket.onopen = (e) => {
  9. this.isOpen = true
  10. while (this.queued.length > 0 && this.isOpen) {
  11. const first = this.queued[0]
  12. this.send(first.action, first.payload)
  13. this.queued = this.queued.slice(1)
  14. }
  15. }
  16. this.socket.onclose = (e) => {
  17. this.isOpen = false
  18. }
  19. this._handleMessage = this._handleMessage.bind(this)
  20. this.socket.onmessage = this._handleMessage
  21. this.close = this.close.bind(this)
  22. this.emit = this.emit.bind(this)
  23. this.on = this.on.bind(this)
  24. this.once = this.once.bind(this)
  25. this.send = this.send.bind(this)
  26. }
  27. close () {
  28. return this.socket.close()
  29. }
  30. send (action, payload) {
  31. // attach uuid
  32. if (!this.isOpen) {
  33. this.queued.push({action, payload})
  34. return
  35. }
  36. this.socket.send(JSON.stringify({
  37. action,
  38. payload
  39. }))
  40. }
  41. on (action, handler) {
  42. console.log(action)
  43. this.emitter.on(action, handler)
  44. }
  45. emit (action, payload) {
  46. console.log(action)
  47. this.emitter.emit(action, payload)
  48. }
  49. once (action, handler) {
  50. this.emitter.once(action, handler)
  51. }
  52. _handleMessage (e) {
  53. try {
  54. const message = JSON.parse(e.data)
  55. console.log(message)
  56. this.emit(message.action, message.payload)
  57. } catch (err) {
  58. console.log(err)
  59. }
  60. }
  61. }