From 8cc52703f0d8c74172dca3b779f2a031f91dd433 Mon Sep 17 00:00:00 2001 From: Aseem Kishore Date: Sun, 17 Nov 2013 00:52:03 -0500 Subject: [PATCH] Serialization (#75): add GraphDatabase::reviveJSON() method. For direct pluggability into JSON.parse()! --- lib/GraphDatabase._coffee | 16 ++++++++++++++++ test/crud._coffee | 25 ++++++++++++++++--------- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/lib/GraphDatabase._coffee b/lib/GraphDatabase._coffee index 577dc27..c06bf1f 100644 --- a/lib/GraphDatabase._coffee +++ b/lib/GraphDatabase._coffee @@ -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: ### # diff --git a/test/crud._coffee b/test/crud._coffee index 40773e9..686e985 100644 --- a/test/crud._coffee +++ b/test/crud._coffee @@ -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': (_) ->