diff --git a/lib/datastore.js b/lib/datastore.js index 5068397..5368249 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -61,6 +61,7 @@ Datastore.prototype.loadDatabase = function () { */ Datastore.treatRawData = function (rawData) { var data = rawData.split('\n') + , dataById = {} , res = [] , i; @@ -69,11 +70,15 @@ Datastore.treatRawData = function (rawData) { try { doc = model.deserialize(data[i]); - if (doc._id) {res.push(doc); } + if (doc._id) { dataById[doc._id] = doc; } } catch (e) { } } + Object.keys(dataById).forEach(function (k) { + res.push(dataById[k]); + }); + return res; }; diff --git a/test/db.test.js b/test/db.test.js index 7945b3d..66b10c9 100644 --- a/test/db.test.js +++ b/test/db.test.js @@ -36,7 +36,7 @@ describe('Database', function () { }); - describe('Loading the database data from file', function () { + describe.only('Loading the database data from file', function () { it('Every line represents a document', function () { var now = new Date() @@ -46,6 +46,7 @@ describe('Database', function () { , treatedData = Datastore.treatRawData(rawData) ; + treatedData.sort(function (a, b) { return a._id - b._id; }); treatedData.length.should.equal(3); _.isEqual(treatedData[0], { _id: "1", a: 2, ages: [1, 5, 12] }).should.equal(true); _.isEqual(treatedData[1], { _id: "2", hello: 'world' }).should.equal(true); @@ -60,6 +61,7 @@ describe('Database', function () { , treatedData = Datastore.treatRawData(rawData) ; + treatedData.sort(function (a, b) { return a._id - b._id; }); treatedData.length.should.equal(2); _.isEqual(treatedData[0], { _id: "1", a: 2, ages: [1, 5, 12] }).should.equal(true); _.isEqual(treatedData[1], { _id: "3", nested: { today: now } }).should.equal(true); @@ -73,11 +75,26 @@ describe('Database', function () { , treatedData = Datastore.treatRawData(rawData) ; + treatedData.sort(function (a, b) { return a._id - b._id; }); treatedData.length.should.equal(2); _.isEqual(treatedData[0], { _id: "1", a: 2, ages: [1, 5, 12] }).should.equal(true); _.isEqual(treatedData[1], { _id: "2", hello: 'world' }).should.equal(true); }); + it('If two lines concern the same doc (= same _id), the last one is the good version', function () { + var now = new Date() + , rawData = model.serialize({ _id: "1", a: 2, ages: [1, 5, 12] }) + '\n' + + model.serialize({ _id: "2", hello: 'world' }) + '\n' + + model.serialize({ _id: "1", nested: { today: now } }) + , treatedData = Datastore.treatRawData(rawData) + ; + + treatedData.sort(function (a, b) { return a._id - b._id; }); + treatedData.length.should.equal(2); + _.isEqual(treatedData[0], { _id: "1", nested: { today: now } }).should.equal(true); + _.isEqual(treatedData[1], { _id: "2", hello: 'world' }).should.equal(true); + }); + }); // ==== End of 'Loading the database data from file' ==== //