Throw error when model relation name is trigger

Defining a model relation with the name "trigger" causes the model not
able to insert records. No error is thrown when a model relation with
the name "trigger" is defined. Adding a check for the model relation
name "trigger" will now throw an error.
This commit is contained in:
Brian Schemp 2016-11-27 15:58:50 -10:00
parent a34f321d2b
commit 65739efe91
2 changed files with 51 additions and 0 deletions

View File

@ -118,6 +118,12 @@ Registry.prototype.createModel = function(name, properties, options) {
}
}
var invalidRelationName = checkRelationName(options);
if (invalidRelationName.length > 0) {
throw new Error(g.f('Invalid relation name `%s` for model `%s`.', invalidRelationName, name));
}
BaseModel = BaseModel || this.getModel('PersistedModel');
var model = BaseModel.extend(name, properties, options);
model.registry = this;
@ -146,6 +152,30 @@ function buildModelOptionsFromConfig(config) {
return options;
}
/*
* Check the name of a model relation name against a list of reserved names.
* @param {Object[]} options
* @return {string} The name of the reserved relation name.
*/
function checkRelationName(options) {
var reservedNames = ['trigger'];
var invalidRelationName = '';
if (options.hasOwnProperty('relations')) {
Object.keys(options['relations']).forEach(function(relationName) {
var isReserved = reservedNames.some(function(reservedName) {
return relationName === reservedName;
});
if (isReserved) {
invalidRelationName = relationName;
}
});
}
return invalidRelationName;
}
/*
* Add the acl entry to the acls
* @param {Object[]} acls

View File

@ -17,6 +17,27 @@ describe('Registry', function() {
expect(function() { app.registry.createModel('aModel', props, opts); })
.to.throw(/model\s`aModel`(.*)unknown\smodel\s`nonexistent`/);
});
it('should throw error upon reserved relation name `trigger`', function() {
var app = loopback();
var fooModel = {
name: 'Foo',
properties: {
name: 'string',
},
options: {
relations: {
trigger: {
model: 'Bar',
type: 'hasMany',
},
},
},
};
expect(function() { app.registry.createModel(fooModel); })
.to.throw('Invalid relation name `trigger` for model `Foo`.');
});
});
describe('one per app', function() {