-
-
Save apueee/5886191 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Backbone.sync = function(method, model, options) { | |
// App.db is my database connection | |
if(_.isNull(App.db)) console.error('No Database connection!'); | |
var query = BackboneDb.createQuery(method, model); | |
if (method === "read") { | |
var data = App.db.execute(query); | |
var resultJSON = BackboneDb.resultToJSON(data); | |
// console.log(data); | |
// console.log(resultJSON); | |
// If it's not a collection, use first value only | |
if(_.isUndefined(model.models)) { | |
resultJSON = resultJSON[0] || null; | |
} | |
// simulate a normal async network call | |
setTimeout(function(){ | |
options.success(resultJSON, 'success', null); | |
}, 0); | |
} | |
}; | |
var BackboneDb = function() { | |
return { | |
resultToJSON: function(rows) { | |
var result = []; | |
while (rows.isValidRow()) { | |
var row = {}; | |
_(rows.fieldCount()).times(function(i){ | |
row[rows.fieldName(i)] = rows.field(i); | |
}); | |
result.push(row); | |
rows.next(); | |
} | |
return result; | |
}, | |
createQuery: function(method, model) { | |
// For models, it's a funciton | |
var url = _.isFunction(model.url)? model.url() : model.url; | |
var parts = _.compact(url.split('/')); | |
if(parts.length === 0) return false; | |
var table = parts[0]; | |
var id = parts[1] || null; | |
var query = null; | |
if(method == 'read'){ | |
query = 'SELECT * FROM ' + table; | |
if(id) { | |
query += ' WHERE id = ' + id; | |
} | |
} | |
return query; | |
} | |
} | |
}(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment