all files / ui/ ResourceManager.js

38.89% Statements 7/18
25% Branches 1/4
40% Functions 2/5
38.89% Lines 7/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                            205× 205× 205×                                             160× 160× 799× 799×                                              
import { forEach } from '../util'
 
/*
  Each time a resource node is created an automatic fetch is triggered. This
  happens only once. We may want to adapt other fetching strategies as well.
 
  TODO: Resources would be problematic in a realtime scenario atm, as all
  collaborators would trigger a fetch of the resource, when it should only
  be done by the user who created the resource explicitly
*/
 
class ResourceManager {
 
  constructor(editorSession, context) {
    this.editorSession = editorSession
    this.context = context
    this.editorSession.onRender('document', this._onDocumentChange, this)
  }
 
  dispose() {
    this.editorSession.off(this)
  }
 
  /*
    Trigger fetch of a given resource
  */
  triggerFetch(resource) {
    resource.fetchPayload(this.context, (err, props) => {
      if (err) {
        this._updateNode(resource.id, {
          errorMessage: err.toString()
        })
      } else {
        this._updateNode(resource.id, props)
      }
    })
  }
 
  _onDocumentChange(change) {
    let doc = this.editorSession.getDocument()
    forEach(change.created, (node) => {
      node = doc.get(node.id)
      Iif (node.constructor.isResource) {
        setTimeout(() => {
          this.triggerFetch(node)
        })
      }
    })
  }
 
  /*
      Fill in node payload
  */
  _updateNode(nodeId, props) {
    let editorSession = this.editorSession
    editorSession.transaction((tx) => {
      forEach(props, (val, key) => {
        tx.set([nodeId, key], val)
      })
    })
  }
}
 
 
export default ResourceManager