|
|
|
@ -1,5 +1,7 @@ |
|
|
|
|
/** |
|
|
|
|
* The datastore itself |
|
|
|
|
* TODO |
|
|
|
|
* Improve serialization (for types such as Dates, handle new lines in strings) |
|
|
|
|
*/ |
|
|
|
|
|
|
|
|
|
var fs = require('fs') |
|
|
|
@ -67,9 +69,41 @@ Datastore.treatRawData = function (rawData) { |
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* Insert a new document |
|
|
|
|
* @param {Function} cb Optional callback, signature: err, insertedDoc |
|
|
|
|
*/ |
|
|
|
|
Datastore.prototype.insert = function (newDoc, cb) { |
|
|
|
|
var callback = cb || function () {} |
|
|
|
|
, self = this |
|
|
|
|
, persistableNewDoc |
|
|
|
|
; |
|
|
|
|
|
|
|
|
|
try { |
|
|
|
|
newDoc._id = customUtils.uid(16); |
|
|
|
|
persistableNewDoc = JSON.stringify(newDoc); |
|
|
|
|
} catch (e) { |
|
|
|
|
return callback(e); |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
fs.appendFile(self.filename, persistableNewDoc + '\n', 'utf8', function (err) { |
|
|
|
|
if (err) { return callback(err); } |
|
|
|
|
|
|
|
|
|
var insertedDoc = JSON.parse(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); |
|
|
|
|
}); |
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
var d = new Datastore('workspace/test.db'); |
|
|
|
|
d.loadDatabase(function (err) { |
|
|
|
|
d.insert({ onetest: "oh yeah" }, function (err, insertedDoc) { |
|
|
|
|
console.log(err); |
|
|
|
|
console.log("==============="); |
|
|
|
|
console.log(insertedDoc); |
|
|
|
|
}); |
|
|
|
|
}); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|