Handle errors in autoload

pull/2/head
Louis Chatriot 11 years ago
parent 35356fd13e
commit 3a2db5f56e
  1. 7
      lib/datastore.js
  2. 40
      test/db.test.js

@ -16,6 +16,7 @@ var customUtils = require('./customUtils')
* @param {Boolean} options.nodeWebkitAppName Optional, specify the name of your NW app if you want options.filename to be relative to the directory where
* Node Webkit stores application data such as cookies and local storage (the best place to store data in my opinion)
* @param {Boolean} options.autoload Optional, defaults to false
* @param {Function} options.onload Optional, if autoload is used this will be called after the load database with the error object as parameter. If you don't pass it the error will be thrown
*/
function Datastore (options) {
var filename;
@ -53,7 +54,11 @@ function Datastore (options) {
this.indexes = {};
this.indexes._id = new Index({ fieldName: '_id', unique: true });
if (this.autoload) { this.loadDatabase(); }
// Queue a load of the database right away and call the onload handler
// By default (no onload handler), if there is an error there, no operation will be possible so warn the user by throwing an exception
if (this.autoload) { this.loadDatabase(options.onload || function (err) {
if (err) { throw err; }
}); }
}

@ -53,6 +53,46 @@ describe('Database', function () {
dbef.inMemoryOnly.should.equal(true);
});
describe('Autoloading', function () {
it('Can autoload a database and query it right away', function (done) {
var fileStr = model.serialize({ _id: '1', a: 5, planet: 'Earth' }) + '\n' + model.serialize({ _id: '2', a: 5, planet: 'Mars' }) + '\n'
, autoDb = 'workspace/auto.db'
, db
;
fs.writeFileSync(autoDb, fileStr, 'utf8');
db = new Datastore({ filename: autoDb, autoload: true })
db.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
done();
});
});
it('Throws if autoload fails', function (done) {
var fileStr = model.serialize({ _id: '1', a: 5, planet: 'Earth' }) + '\n' + model.serialize({ _id: '2', a: 5, planet: 'Mars' }) + '\n' + '{"$$indexCreated":{"fieldName":"a","unique":true}}'
, autoDb = 'workspace/auto.db'
, db
;
fs.writeFileSync(autoDb, fileStr, 'utf8');
// Check the loadDatabase generated an error
function onload (err) {
err.errorType.should.equal('uniqueViolated');
done();
}
db = new Datastore({ filename: autoDb, autoload: true, onload: onload })
db.find({}, function (err, docs) {
done("Find should not be executed since autoload failed");
});
});
});
describe('Insert', function () {

Loading…
Cancel
Save