From 65739efe9191e48903595b950e0b9c5145426814 Mon Sep 17 00:00:00 2001 From: Brian Schemp Date: Sun, 27 Nov 2016 15:58:50 -1000 Subject: [PATCH] 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. --- lib/registry.js | 30 ++++++++++++++++++++++++++++++ test/registries.test.js | 21 +++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/lib/registry.js b/lib/registry.js index 363c6686..114db3b0 100644 --- a/lib/registry.js +++ b/lib/registry.js @@ -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 diff --git a/test/registries.test.js b/test/registries.test.js index ba0da90d..47eda0e5 100644 --- a/test/registries.test.js +++ b/test/registries.test.js @@ -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() {