From 7f073a4622cf9ecc6ed4eb554a24bc664d03aeb5 Mon Sep 17 00:00:00 2001 From: Anatoliy Chakkaev Date: Thu, 1 Mar 2012 21:26:52 +0400 Subject: [PATCH] Test belongsTo --- lib/abstract-class.js | 10 +++++++--- test/common_test.js | 18 +++++++++++++++++- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/lib/abstract-class.js b/lib/abstract-class.js index c70445f5..3904a8ef 100644 --- a/lib/abstract-class.js +++ b/lib/abstract-class.js @@ -490,6 +490,8 @@ AbstractClass.hasMany = function (anotherClass, params) { AbstractClass.belongsTo = function (anotherClass, params) { var methodName = params.as; var fk = params.foreignKey; + + this.schema.defineForeignKey(this.modelName, fk); this.prototype['__finders__'] = this.prototype['__finders__'] || {} this.prototype['__finders__'][methodName] = function (id, cb) { @@ -508,12 +510,14 @@ AbstractClass.belongsTo = function (anotherClass, params) { this[fk] = p.id; this.cachedRelations[methodName] = p; } else if (typeof p === 'function') { // acts as async getter - this.__finders__[methodName](this[fk],p); - } else if (!p) { // acts as sync getter + this.__finders__[methodName](this[fk], p); return this[fk]; + } else if (typeof p === 'undefined') { // acts as sync getter + return this[fk]; + } else { // setter + this[fk] = p; } }; - console.log(this.prototype); }; diff --git a/test/common_test.js b/test/common_test.js index a5cb562c..b0c41fef 100644 --- a/test/common_test.js +++ b/test/common_test.js @@ -46,7 +46,7 @@ Object.keys(schemas).forEach(function (schemaName) { function testOrm(schema) { - var Post, User; + var Post, User, Passport; var start = Date.now(); it('should define class', function (test) { @@ -92,6 +92,12 @@ function testOrm(schema) { // post.author() -- sync getter when called without params // post.author(user) -- setter when called with object + Passport = schema.define('Passport', { + number: String + }); + + Passport.belongsTo(User, {as: 'owner', foreignKey: 'ownerId'}); + var user = new User; test.ok(User instanceof Function); @@ -598,6 +604,16 @@ function testOrm(schema) { }); }); + it('should handle belongsTo correctly', function (test) { + var passport = new Passport({ownerId: 16}); + // sync getter + test.equal(passport.owner(), 16); + // sync setter + passport.owner(18); + test.equal(passport.owner(), 18); + test.done(); + }); + it('all tests done', function (test) { test.done(); process.nextTick(allTestsDone);