Add ability to attach data source to an existing model

This commit is contained in:
Ritchie 2013-05-23 16:38:14 -07:00
parent 2c2768e929
commit 1dee840de5
3 changed files with 52 additions and 8 deletions

View File

@ -146,6 +146,7 @@ DataAccessObject.create = function (data, callback) {
}, obj);
}
// for chaining
return obj;
};
@ -308,6 +309,13 @@ DataAccessObject.all = function all(params, cb) {
});
};
// shared by default
DataAccessObject.all.accepts = {arg: 'filter', type: 'object'};
DataAccessObject.all.shared = true;
DataAccessObject.all.http = {
}
/**
* Find one record, same as `all`, limited by 1 and return object, not collection
*

View File

@ -55,10 +55,16 @@ function DataSource(name, settings) {
}
ADL.call(this);
this.setup(name, settings);
// default DataAccessObject
this.DataAccessObject = this.constructor.DataAccessObject;
};
util.inherits(DataSource, ADL);
// allow child classes to supply a data access object
DataSource.DataAccessObject = DataAccessObject;
// Copy over statics
for (var m in ADL) {
if (!DataSource.hasOwnProperty(m) && 'super_' !== m) {
@ -198,13 +204,8 @@ DataSource.prototype.define = function defineClass(className, properties, settin
var NewClass = ADL.prototype.define.call(this, className, properties, settings);
// inherit DataAccessObject methods
for (var m in DataAccessObject) {
NewClass[m] = DataAccessObject[m];
}
for (var n in DataAccessObject.prototype) {
NewClass.prototype[n] = DataAccessObject.prototype[n];
}
// add data access objects
this.mixin(NewClass);
if(this.adapter) {
// pass control to adapter
@ -219,6 +220,41 @@ DataSource.prototype.define = function defineClass(className, properties, settin
};
/**
* Mixin DataAccessObject methods.
*/
DataSource.prototype.mixin = function (ModelCtor) {
var DataAccessObject = this.DataAccessObject;
// inherit DataAccessObject methods
for (var m in DataAccessObject) {
ModelCtor[m] = DataAccessObject[m];
}
for (var n in DataAccessObject.prototype) {
ModelCtor.prototype[n] = DataAccessObject.prototype[n];
}
}
/**
* Attach an existing model to a data source.
*/
DataSource.prototype.attach = function (ModelCtor) {
this.mixin(ModelCtor);
if(this.adapter) {
// pass control to adapter
this.adapter.define({
model: ModelCtor,
properties: ModelCtor.properties,
settings: ModelCtor.settings
});
}
return this;
}
/**
* Define single property named `prop` on `model`
*

View File

@ -6,6 +6,7 @@ module.exports = ModelBaseClass;
/**
* Module dependencies
*/
var util = require('util');
var List = require('./list.js');
require('./hooks.js');
@ -230,7 +231,6 @@ ModelBaseClass.prototype.inspect = function () {
return util.inspect(this.__data, false, 4, true);
};
/**
* Check whether `s` is not undefined
* @param {Mixed} s