Skip to content

Commit

Permalink
Serialization (#75): add GraphDatabase::reviveJSON() method.
Browse files Browse the repository at this point in the history
For direct pluggability into JSON.parse()!
  • Loading branch information
aseemk committed Nov 17, 2013
1 parent 1aab92f commit 8cc5270
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
16 changes: 16 additions & 0 deletions lib/GraphDatabase._coffee
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,22 @@ module.exports = class GraphDatabase
Constructor = require "./#{constructor}"
Constructor.fromJSON @, obj

#
# A "reviver" function for JSON.parse() that'll transform any serialized
# nodes or relationships into their appropriate instances.
#
# To use, pass this method as the second parameter to JSON.parse().
# For convenience, it'll be bound to this GraphDatabase instance.
#
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
#
reviveJSON: (k, v) =>
# only transform objects we recognize; ignore (pass through) the rest:
if v?.package?.name is PACKAGE.name
@fromJSON v
else
v

### Misc/Other: ###

#
Expand Down
25 changes: 16 additions & 9 deletions test/crud._coffee
Original file line number Diff line number Diff line change
Expand Up @@ -151,23 +151,30 @@ relCustomIndexName2 = 'testFollowsFullTextNoLowercase'
expect(relationship.end).to.eq aseem

'serialize & de-serialize nodes': (_) ->
aseemJSON = JSON.stringify aseem
danielJSON = JSON.stringify daniel
json = JSON.stringify [aseem, daniel]
obj = JSON.parse json, db.reviveJSON

aseemObj = JSON.parse aseemJSON
danielObj = JSON.parse danielJSON
expect(obj).to.be.an 'array'
expect(obj).to.have.length 2

aseem2 = db.fromJSON aseemObj
daniel2 = db.fromJSON danielObj
[aseem2, daniel2] = obj

expect(aseem2).to.be.an 'object'
expect(aseem2.data).to.eql aseem.data

expect(daniel2).to.be.an 'object'
expect(daniel2.data).to.eql daniel.data

'serialize & de-serialize relationship': (_) ->
relJSON = JSON.stringify relationship
relObj = JSON.parse relJSON
rel2 = db.fromJSON relObj
json = JSON.stringify {foo: {bar: relationship}}
obj = JSON.parse json, db.reviveJSON

expect(obj).to.be.an 'object'
expect(obj.foo).to.be.an 'object'

rel2 = obj.foo.bar

expect(rel2).to.be.an 'object'
expect(rel2.data).to.eql relationship.data

'fetch relationships': (_) ->
Expand Down

0 comments on commit 8cc5270

Please sign in to comment.