From d6da8b7d8df6fed8aea7e1f0cdaddbe09e6ff97b Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Thu, 2 May 2013 19:03:20 +0200 Subject: [PATCH] Externalize serialization and deserialization --- lib/datastore.js | 9 +++++---- lib/model.js | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 lib/model.js diff --git a/lib/datastore.js b/lib/datastore.js index f0518e2..1b6dc7b 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -10,6 +10,7 @@ var fs = require('fs') , path = require('path') , customUtils = require('./customUtils') + , model = require('./model') ; @@ -62,7 +63,7 @@ Datastore.treatRawData = function (rawData) { var doc; try { - doc = JSON.parse(d); + doc = model.deserialize(d); res.push(doc); } catch (e) { } @@ -84,7 +85,7 @@ Datastore.prototype.insert = function (newDoc, cb) { try { newDoc._id = customUtils.uid(16); - persistableNewDoc = JSON.stringify(newDoc); + persistableNewDoc = model.serialize(newDoc); } catch (e) { return callback(e); } @@ -92,7 +93,7 @@ Datastore.prototype.insert = function (newDoc, cb) { fs.appendFile(self.filename, persistableNewDoc + '\n', 'utf8', function (err) { if (err) { return callback(err); } - var insertedDoc = JSON.parse(persistableNewDoc); + var insertedDoc = model.deserialize(persistableNewDoc); self.data.push(insertedDoc); // Make sure the doc is the same on the disk and in memory // Some docs can't be stringified correctly return callback(null, insertedDoc); @@ -174,7 +175,7 @@ Datastore.prototype.persistWholeDatabase = function (data, cb) { callback = cb || function () {}; data.forEach(function (d) { - newContents += JSON.stringify(d) + '\n'; + newContents += model.serialize(d) + '\n'; }); fs.writeFile(self.filename, newContents, 'utf8', callback); diff --git a/lib/model.js b/lib/model.js new file mode 100644 index 0000000..2edf1b1 --- /dev/null +++ b/lib/model.js @@ -0,0 +1,19 @@ +/** + * Handle models (i.e. docs) + * Serialization/deserialization + * Copying + */ + +function serialize (obj) { + return JSON.stringify(obj); +} + +function deserialize (rawData) { + return JSON.parse(rawData); +} + + +// Interface +module.exports.serialize = serialize; +module.exports.deserialize = deserialize; +