This will get quite clumsy if I continue down the road with this design, so I'm asking you, enlightened ones, is there a way to make this prettier and easier to understand? Primarily the run
-function (Especially in the else if
where self.query
and self.find
are set), also, I want it to be chain-able, with .run
being the last function.
db = function(dir){
if(dir[dir.length - 1] == "/") this.dir = dir.slice(0, -1);
else this.dir = dir;
return this;
}
db.prototype.table = function(table){
this.table = table;
return this;
}
db.prototype.put = function(obj){
this.put = obj;
return this;
}
db.prototype.find = function(query){
this.query = query;
this.find = "all";
return this;
}
db.prototype.pluck = function(){
this.pluck = arguments;
return this;
}
db.prototype.run = function(callback){
var self = JSON.parse(JSON.stringify(this));
for(var key in this){
if(typeof this[key] != "function" && key != "dir" && key != "table") delete this[key];
}
helper.mkdb(self, function(err, created){
helper.mktbl(self, function(err, created){
var docs = [];
if(self.put){
helper.put(self, function(err, docs){
callback(err, docs);
})
}else if(self.query && self.find){
helper.find(self, function(err, docs){
if(err) callback(err);
else{
self.docs = docs;
if(self.pluck){
helper.pluck(self, function(err, docs){
callback(err, docs);
})
}else{
callback(err, docs);
}
}
})
}else if(self.pluck){
helper.pluck(self, function(err, docs){
callback(err, docs);
})
}else callback(new Error("Cannot execute \".run()\" without any functions before it"));
})
});
}