all files / model/ JSONConverter.js

88.89% Statements 16/18
70% Branches 7/10
100% Functions 5/5
88.89% Lines 16/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                                                  24× 24×              
import { forEach } from '../util'
 
class JSONConverter {
 
  importDocument(doc, json) {
    Iif (!json.nodes) {
      throw new Error('Invalid JSON format.')
    }
    var schema = doc.getSchema()
    Iif (json.schema && schema.name !== json.schema.name) {
      throw new Error('Incompatible schema.')
    }
    // the json should just be an array of nodes
    var nodes = json.nodes
    // import data in a block with deactivated indexers and listeners
    // as the data contains cyclic references which
    // cause problems.
    doc.import(function(tx) {
      forEach(nodes, function(node) {
        // overwrite existing nodes
        if (tx.get(node.id)) {
          tx.delete(node.id)
        }
        tx.create(node)
      })
    })
    return doc
  }
 
  exportDocument(doc) {
    var schema = doc.getSchema()
    var json = {
      schema: {
        name: schema.name
      },
      nodes: {}
    }
    forEach(doc.getNodes(), function(node) {
      Eif (node._isDocumentNode) {
        json.nodes[node.id] = node.toJSON()
      }
    })
    return json
  }
}
 
export default JSONConverter