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

Better preparation for cloned object serialization #134

Merged
merged 1 commit into from
Mar 1, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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