@@ -32,13 +32,19 @@ exports.prepare = function (db, Model, associations, association_properties, mod
3232 } ;
3333} ;
3434
35- exports . extend = function ( Model , Instance , Driver , associations , opts , cb ) {
35+ exports . extend = function ( Model , Instance , Driver , associations , opts ) {
36+ for ( var i = 0 ; i < associations . length ; i ++ ) {
37+ extendInstance ( Model , Instance , Driver , associations [ i ] , opts ) ;
38+ }
39+ } ;
40+
41+ exports . autoFetch = function ( Instance , associations , opts , cb ) {
3642 if ( associations . length === 0 ) {
3743 return cb ( ) ;
3844 }
3945
4046 var pending = associations . length ;
41- var extendDone = function extendDone ( ) {
47+ var autoFetchDone = function autoFetchDone ( ) {
4248 pending -= 1 ;
4349
4450 if ( pending === 0 ) {
@@ -47,11 +53,11 @@ exports.extend = function (Model, Instance, Driver, associations, opts, cb) {
4753 } ;
4854
4955 for ( var i = 0 ; i < associations . length ; i ++ ) {
50- extendInstance ( Model , Instance , Driver , associations [ i ] , opts , extendDone ) ;
56+ autoFetchInstance ( Instance , associations [ i ] , opts , autoFetchDone ) ;
5157 }
5258} ;
5359
54- function extendInstance ( Model , Instance , Driver , association , opts , cb ) {
60+ function extendInstance ( Model , Instance , Driver , association , opts ) {
5561 Object . defineProperty ( Instance , association . hasAccessor , {
5662 value : function ( cb ) {
5763 if ( ! Instance [ Model . id ] ) {
@@ -129,8 +135,28 @@ function extendInstance(Model, Instance, Driver, association, opts, cb) {
129135 } ,
130136 enumerable : false
131137 } ) ;
138+ }
139+
140+ function autoFetchInstance ( Instance , association , opts , cb ) {
141+ if ( ! opts . hasOwnProperty ( "autoFetchLimit" ) || typeof opts . autoFetchLimit == "undefined" ) {
142+ opts . autoFetchLimit = association . autoFetchLimit ;
143+ }
144+
145+ if ( opts . autoFetchLimit === 0 || ( ! opts . autoFetch && ! association . autoFetch ) ) {
146+ return cb ( ) ;
147+ }
148+
149+ if ( Instance . isPersisted ( ) ) {
150+ Instance [ association . getAccessor ] ( { autoFetchLimit : opts . autoFetchLimit - 1 } , function ( err , Assoc ) {
151+ if ( ! err ) {
152+ Instance [ association . name ] = Assoc ;
153+ }
132154
133- return cb ( ) ;
155+ return cb ( ) ;
156+ } ) ;
157+ } else {
158+ return cb ( ) ;
159+ }
134160}
135161
136162function ucfirst ( text ) {
0 commit comments