Skip to content

Commit

Permalink
toJSON checks for Realm.Object or Realm.Collection before calling toJ…
Browse files Browse the repository at this point in the history
…SON recursively.
  • Loading branch information
steffenagger committed Aug 12, 2020
1 parent b3176bb commit 4c39b07
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/extensions.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ module.exports = function(realmConstructor, context) {

Object.defineProperty(realmConstructor.Collection.prototype, "toJSON", {
value: function (_, cache = new Map()) {
return this.map((item, index) => item.toJSON ? item.toJSON(index.toString(), cache) : item);
return this.map((item, index) =>
item instanceof realmConstructor.Object ? item.toJSON(index.toString(), cache) : item);
},

writable: true,
Expand Down Expand Up @@ -112,8 +113,10 @@ module.exports = function(realmConstructor, context) {
Object.keys(this)
.concat(Object.keys(Object.getPrototypeOf(this)))
.forEach(key => {
// TODO: check that we're dealing with a Realm type, before passing in cache?
result[key] = this[key].toJSON ? this[key].toJSON(key, cache) : this[key];
const value = this[key];
result[key] = value instanceof realmConstructor.Object || value instanceof realmConstructor.Collection
? value.toJSON(key, cache)
: value;
});

return result;
Expand Down

0 comments on commit 4c39b07

Please sign in to comment.