Externalize serialization and deserialization

pull/2/head
Louis Chatriot 12 years ago
parent d40601785c
commit d6da8b7d8d
  1. 9
      lib/datastore.js
  2. 19
      lib/model.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);

@ -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;
Loading…
Cancel
Save