From 0d9eebe3bb0f065c973d869d6ebba10a4c06d53a Mon Sep 17 00:00:00 2001 From: Jue Hou Date: Mon, 18 Jan 2016 21:48:58 -0500 Subject: [PATCH] Prevent constructor to be property name --- lib/model-builder.js | 6 ++++++ lib/model.js | 5 +++++ test/model-definition.test.js | 17 +++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/lib/model-builder.js b/lib/model-builder.js index b36e4d41..b100a3d8 100644 --- a/lib/model-builder.js +++ b/lib/model-builder.js @@ -257,6 +257,12 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett deprecated('Property names containing a dot are not supported. ' + 'Model: ' + className + ', property: ' + p); } + + // Warn if property name is 'constructor' + if (p === "constructor") { + deprecated('Property name should not be "constructor" in Model: ' + + className); + } } var modelDefinition = new ModelDefinition(this, className, properties, settings); diff --git a/lib/model.js b/lib/model.js index e701f81c..2cdab73d 100644 --- a/lib/model.js +++ b/lib/model.js @@ -63,6 +63,11 @@ ModelBaseClass.prototype._initProperties = function (data, options) { var self = this; var ctor = this.constructor; + if (typeof data !== 'undefined' && + typeof (data.constructor) !== 'function') { + throw new Error('Property name "constructor" is not allowed in ' + ctor.modelName +' data'); + } + if(data instanceof ctor) { // Convert the data to be plain object to avoid pollutions data = data.toObject(false); diff --git a/test/model-definition.test.js b/test/model-definition.test.js index b7ac4c63..c2ce3d2a 100644 --- a/test/model-definition.test.js +++ b/test/model-definition.test.js @@ -379,6 +379,15 @@ describe('ModelDefinition class', function () { message.should.match(/Dotted.*dot\.name/); }); + it('should report deprecation warning for property named constructor', function() { + var message = 'deprecation not reported'; + process.once('deprecation', function(err) { message = err.message; }); + + memory.createModel('Ctor', { 'constructor': String }); + + message.should.match(/Property name should not be "constructor" in Model: Ctor/); + }); + it('should report deprecation warning for dynamic property names containing dot', function(done) { var message = 'deprecation not reported'; process.once('deprecation', function(err) { message = err.message; }); @@ -391,6 +400,14 @@ describe('ModelDefinition class', function () { }); }); + it('should throw error for dynamic property named constructor', function(done) { + var Model = memory.createModel('DynamicCtor'); + Model.create({ 'constructor': 'myCtor' }, function(err) { + assert.equal(err.message, 'Property name "constructor" is not allowed in DynamicCtor data'); + done(); + }); + }); + it('should support "array" type shortcut', function() { var Model = memory.createModel('TwoArrays', { regular: Array,