scope-like remotable metadata for belongsTo

Modify the methods created by `belongsTo` relation to mimick the methods
created by scopes (e.g. via `hasMany` relation).

This allows client code generators like loopback-angular to use the same
code for all relation types.
This commit is contained in:
Miroslav Bajtoš 2014-04-08 10:30:57 +02:00
parent 3806682eb4
commit 440dfaf3a7
1 changed files with 17 additions and 8 deletions

View File

@ -347,14 +347,6 @@ Relation.belongsTo = function (anotherClass, params) {
// Call the relation method on the declaring model instance
return relationMethod.apply(this, arguments);
}
// Set the remoting metadata so that it can be accessed as /api/<model>/<id>/<belongsToRelationName>
// For example, /api/orders/1/customer
fn.shared = true;
fn.http = {verb: 'get', path: '/' + methodName};
fn.accepts = {arg: 'refresh', type: 'boolean', http: {source: 'query'}};
fn.description = 'Fetches belongsTo relation ' + methodName;
fn.returns = {arg: methodName, type: 'object', root: true};
// Create an instance of the target model and set the foreign key of the
// declaring model instance to the id of the target instance
fn.create = function(targetModelData, cb) {
@ -374,9 +366,26 @@ Relation.belongsTo = function (anotherClass, params) {
return new anotherClass(targetModelData);
}.bind(this);
fn._targetClass = anotherClass.modelName;
return fn;
}});
// Wrap the property into a function for remoting
// so that it can be accessed as /api/<model>/<id>/<belongsToRelationName>
// For example, /api/orders/1/customer
var fn = function() {
var f = this[methodName];
f.apply(this, arguments);
};
fn.shared = true;
fn.http = {verb: 'get', path: '/' + methodName};
fn.accepts = {arg: 'refresh', type: 'boolean', http: {source: 'query'}};
fn.description = 'Fetches belongsTo relation ' + methodName;
fn.returns = {arg: methodName, type: 'object', root: true};
this.prototype['__get__' + methodName] = fn;
};
/**