Skip to content
This repository has been archived by the owner on Dec 4, 2018. It is now read-only.

Commit

Permalink
Merge pull request #134 from bugsnag/mongo-objectid-serialization
Browse files Browse the repository at this point in the history
Better preparation for cloned object serialization
  • Loading branch information
bengourley authored Mar 1, 2018
2 parents 2213c6d + 50cb616 commit 1d6bf8c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 12 deletions.
26 changes: 15 additions & 11 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,18 @@ var Utils = {
return clonedResults[existingIdx];
}

var copy = obj;
var type = Utils.typeOf(obj);
var orig = obj
var maybeJsonified = (Utils.typeOf(obj) === "object" && typeof obj.toJSON === 'function') ? obj.toJSON() : obj;
var type = Utils.typeOf(maybeJsonified);

if (type === "object") {
copy = {};
clonedSources.push(obj);
var copy = {};
clonedSources.push(orig);
clonedResults.push(copy);

Object.keys(obj).forEach(function (key) {
var val = obj[key];
if (!Utils.checkOwnProperty(obj, key)) {
Object.keys(maybeJsonified).forEach(function (key) {
var val = maybeJsonified[key];
if (!Utils.checkOwnProperty(maybeJsonified, key)) {
return;
}

Expand All @@ -90,14 +91,17 @@ var Utils = {

copy[key] = Utils.cloneObject(val, options);
});
return copy;
} else if (type === "array") {
copy = [];
clonedSources.push(obj);
var copy = [];
clonedSources.push(maybeJsonified);
clonedResults.push(copy);

for (var i = 0; i < obj.length; ++i) {
copy.push(Utils.cloneObject(obj[i], options));
for (var i = 0; i < maybeJsonified.length; ++i) {
copy.push(Utils.cloneObject(maybeJsonified[i], options));
}
} else {
copy = maybeJsonified
}

return copy;
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"stack-trace": "~0.0.9"
},
"devDependencies": {
"bson-objectid": "^1.2.2",
"chai": "~1.5.0",
"coveralls": "^2.13.1",
"cuid": "^1.3.8",
Expand Down
13 changes: 12 additions & 1 deletion test/utils.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"use strict";

var should = require("chai").should(),
Utils = require("../lib/utils");
Utils = require("../lib/utils"),
ObjectID = require("bson-objectid");

describe("utils", function() {
describe("typeOf", function() {
Expand Down Expand Up @@ -135,6 +136,16 @@ describe("utils", function() {
clone.should.have.keys("firstKey", "secondKey");
return clone.secondKey.should.be.an("object");
});

it("should call an object's toJSON (if it exists) before copying", function () {
var source = {
oid: ObjectID()
};
var clone = Utils.cloneObject(source);
should.exist(clone);
clone.should.have.keys("oid");
(typeof clone.oid).should.equal("string");
});
});

describe("mergeObjects", function() {
Expand Down

0 comments on commit 1d6bf8c

Please sign in to comment.