Home Reference Source

packages/oo7-substrate/src/subscriptionBond.js

  1. const { Bond } = require('oo7')
  2. const { nodeService } = require('./nodeService')
  3.  
  4. class SubscriptionBond extends Bond {
  5. constructor (name, params = [], xform = null, def = undefined, cache = { id: null, stringify: JSON.stringify, parse: JSON.parse }, mayBeNull) {
  6. super(mayBeNull, cache)
  7. this._name = name
  8. this._params = params
  9. this._xform = xform
  10. if (typeof def !== 'undefined' && (def !== null || mayBeNull)) {
  11. this._value = def
  12. this._ready = true
  13. }
  14. }
  15.  
  16. initialise () {
  17. let that = this
  18. let callback = result => {
  19. if (that._xform) {
  20. result = that._xform(result)
  21. }
  22. that.trigger(result)
  23. }
  24. // promise instead of id because if a dependency triggers finalise() before id's promise is resolved the unsubscribing would call with undefined
  25. this.subscription = nodeService().subscribe(this._name, this._params, callback, error => {
  26. that.trigger({failed: error})
  27. console.warn('Failed subscription:', error)
  28. delete that.subscription
  29. })
  30. }
  31. finalise () {
  32. let that = this
  33. this.subscription.then(id => {
  34. nodeService().unsubscribe(id)
  35. delete that.subscription
  36. });
  37. }
  38. }
  39.  
  40. module.exports = { SubscriptionBond }