Skip to content
Browse files

enhancing toJSON and toObject to pump out cached relations, optionally

  • Loading branch information...
1 parent 39f8c9d commit ea826970d06ed96c301a09d3a9b29c1eb02e2e28 @mshick mshick committed Feb 5, 2014
Showing with 17 additions and 7 deletions.
  1. +17 −7 lib/model.js
View
24 lib/model.js
@@ -380,7 +380,7 @@ AbstractClass.upsert = AbstractClass.updateOrCreate = function upsert(data, call
/**
* Find one record, same as `all`, limited by 1 and return object, not collection,
* if not found, create using data provided as second argument
- *
+ *
* @param {Object} query - search conditions: {where: {test: 'me'}}.
* @param {Object} data - object to create.
* @param {Function} cb - callback called with (err, instance)
@@ -585,7 +585,7 @@ AbstractClass.iterate = function map(filter, iterator, callback) {
/**
* Find one record, same as `all`, limited by 1 and return object, not collection
- *
+ *
* @param {Object} params - search conditions: {where: {test: 'me'}}
* @param {Function} cb - callback called with (err, instance)
*/
@@ -673,7 +673,7 @@ AbstractClass.prototype.save = function (options, callback) {
if (!this.id) {
// Pass options and this to create
- var data = {
+ var data = {
data: this,
options: options
};
@@ -734,11 +734,11 @@ AbstractClass.prototype._adapter = function () {
* Convert instance to Object
*
* @param {Boolean} onlySchema - restrict properties to schema only, default false
- * when onlySchema == true, only properties defined in schema returned,
+ * when onlySchema == true, only properties defined in schema returned,
* otherwise all enumerable properties returned
* @returns {Object} - canonical object representation (no getters and setters)
*/
-AbstractClass.prototype.toObject = function (onlySchema) {
+AbstractClass.prototype.toObject = function (onlySchema, cachedRelations) {
var data = {};
var ds = this.constructor.schema.definitions[this.constructor.modelName];
var properties = ds.properties;
@@ -760,6 +760,15 @@ AbstractClass.prototype.toObject = function (onlySchema) {
data[attr] = self[attr];
}
});
+
+ if (cachedRelations === true && this.__cachedRelations) {
+ var relations = this.__cachedRelations;
+ Object.keys(relations).forEach(function (attr) {
+ if (!data.hasOwnProperty(attr)) {
+ data[attr] = relations[attr];
+ }
+ });
+ }
}
return data;
@@ -770,10 +779,11 @@ AbstractClass.prototype.toObject = function (onlySchema) {
// Object.getOwnPropertyNames(this).indexOf(prop) !== -1;
// };
-AbstractClass.prototype.toJSON = function () {
- return this.toObject();
+AbstractClass.prototype.toJSON = function (cachedRelations) {
+ return this.toObject(false, cachedRelations);
};
+
/**
* Delete object from persistence
*

0 comments on commit ea82697

Please sign in to comment.
Something went wrong with that request. Please try again.