      1 var comb = require("comb"),
      2         hitch = comb.hitch,
      3         Promise = comb.Promise,
      4         PromiseList = comb.PromiseList,
      5         _Association = require("./_Association");
      6 /**
      7  * @class Class to define a many to one association.
      8  *
      9  * </br>
     10  * <b>NOT to be instantiated directly</b>
     11  * Its just documented for reference.
     12  *
     13  * @name ManyToOne
     14  * @augments _Association
     15  *
     16  * */
     17 module.exports = exports = comb.define(_Association, {
     18     instance : {
     19         _fetchMethod : "one",
     20
     21         //override
     22         //@see _Association
     23         _postLoad : function(next, self) {
     24             if (self.isEager()) {
     25                 self.fetch(this).then(hitch(this, function(result) {
     26                     this[self.loadedKey] = true;
     27                     this["_" + self.name] = result;
     28                     next();
     29                 }));
     30             } else {
     31                 next();
     32             }
     33         },
     34
     35         //override
     36         //@see _Association
     37         _getter : function(self) {
     38             //if we have them return them;
     39             var loadedKey = self.loadedKey, name = self.name;
     40             //todo make all lazy models always return a Promise
     41             if (this[loadedKey]) return this["_" + name];
     42             //Else we dont have
     43             if (this.isNew) throw new Error("Model is a new object and no associations have been fetched");
     44             var retPromise = new Promise();
     45             self.fetch(this).then(hitch(this, function(result) {
     46                 this[loadedKey] = true;
     47                 var m = result;
     48                 this["_" + name] = m;
     49                 retPromise.callback(m);
     50             }), hitch(retPromise, "errback"));
     51             return retPromise;
     52         },
     53
     54         //override
     55         //@see _Association
     56         _setter : function(cal, self) {
     57             var name = self.name;
     58             if (this.isNew) {
     59                 if (!(val instanceof self.model)) {
     60                     val = new self.model(val);
     61                 }
     62                 this["_" + name] = val;
     63             } else {
     64                 //set my foreign key
     65                 if (!(val instanceof self.model)) {
     66                     val = new self.model(val);
     67                 }
     68                 this[self.leftKey] = val[self.rightKey];
     69                 this["_" + name] = val;
     70             }
     71         }
     72     }
     73 });