node.js - Generic JavaScript Models using Composition -
i working on node.js application couple of javascript model this:
function role(data) { this.data = data; ... } role.prototype.save = function(...) {...} role.findbyid = function(...) {...} role.findall = function(...) {...}
all of them using same (similar) logic of functions, need different implementation saving , on. idea refactor them using kind of composition. current solution combination of using inheritance prototype functions , adapter static functions. looks this.
var _adapter = new databaseadapter(schema, table, role); function role(data) { model.call(this, _adapter, role._attributes) this.data = data; ... } role._attributes = { name: '' } role.prototype.save = function(...) {...} role.findbyid = function(...) { _adapter.findbyid(...); } role.findall = function(...) { _adapter.findall(...) }
but, not happy current solution, because developers need know lot of implementation details create new model. so, hope show me better approach solve problem.
thanks, hendrik
edit after research came following solution:
role model:
role.schema = 'db-schema-name'; role.table = 'db-table-name'; role.attributes = { /* attributes of model */ } role.prototype.save = genericsavefunc; role.findbyid = genericfindbyidfunc; ...
generic save:
function genericsavefunc(...) { if (this.id) { // handle update // attributes in 'this' updated } else { // handle create // attributes in 'this' updated } }
static generic function findbyid:
function genericfindbyidfunc(...) { /* use this.schema && this.table create correct select statement */ }
the model creation wrapped factory function. part of solution simple creation of new models different kind of functionality (e.g add save
, findbyid
model). don't know if idea rely on calling context of generic functions?
since using prototype-based language. there no need try class-inheritance. take @ stampit make easy composition javascript way :)
Comments
Post a Comment