From fbe04233ccd9a2b2394e40c93492f0d4e0d15729 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Drouyer?= Date: Sun, 16 Dec 2012 19:44:14 +0100 Subject: [PATCH] added some documentation for include and all function --- lib/abstract-class.js | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/lib/abstract-class.js b/lib/abstract-class.js index eb278a07..708af0c2 100644 --- a/lib/abstract-class.js +++ b/lib/abstract-class.js @@ -301,6 +301,7 @@ AbstractClass.find = function find(id, cb) { * @param {Object} params (optional) * * - where: Object `{ key: val, key2: {gt: 'val2'}}` + * - include: String, Object or Array. See AbstractClass.include documentation. * - order: String * - limit: Number * - skip: Number @@ -392,16 +393,32 @@ AbstractClass.count = function (where, cb) { }; /** + * Allows you to load relations of several objects and optimize numbers of requests. * + * @param {Array} objects - array of instances + * @param {String}, {Object} or {Array} include - which relations you want to load. + * @param {Function} cb - Callback called when relations are loaded + * + * Examples: + * + * - User.include(users, 'posts', function() {}); will load all users posts with only one additional request. + * - User.include(users, ['posts'], function() {}); // same + * - User.include(users, ['posts', 'passports'], function() {}); // will load all users posts and passports with two + * additional requests. + * - Passport.include(passports, {owner: 'posts'}, function() {}); // will load all passports owner (users), and all + * posts of each owner loaded + * - Passport.include(passports, {owner: ['posts', 'passports']}); // ... + * - Passport.include(passports, {owner: [{posts: 'images'}, 'passports']}); // ... * - * @param objects - * @param include */ -AbstractClass.include = function (objects, include, callback) { +AbstractClass.include = function (objects, include, cb) { var self = this; - if ((include.constructor.name == 'Array' && include.length == 0) || (include.constructor.name == 'Object' && Object.keys(include).length == 0)) { - callback(null, objects); + if ( + (include.constructor.name == 'Array' && include.length == 0) || + (include.constructor.name == 'Object' && Object.keys(include).length == 0) + ) { + cb(null, objects); return; } @@ -412,13 +429,13 @@ AbstractClass.include = function (objects, include, callback) { var nbCallbacks = 0; for (var i = 0; i < include.length; i++) { - var cb = processIncludeItem(objects, include[i], keyVals, objsByKeys); - if (cb !== null) { + var callback = processIncludeItem(objects, include[i], keyVals, objsByKeys); + if (callback !== null) { nbCallbacks++; - cb(function() { + callback(function() { nbCallbacks--; if (nbCallbacks == 0) { - callback(null, objects); + cb(null, objects); } }); }