Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
44 changes: 44 additions & 0 deletions spec/logger.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,50 @@ describe("logger", () => {
});
});

it("should not detect duplicate object as circular", () => {
const obj: any = { a: "foo" };
const entry: logger.LogEntry = {
severity: "ERROR",
message: "testing circular",
a: obj,
b: obj,
};
logger.write(entry);
expectStderr({
severity: "ERROR",
message: "testing circular",
a: { a: "foo" },
b: { a: "foo" },
});
});

it("should not detect duplicate object in array as circular", () => {
const obj: any = { a: "foo" };
const arr: any = [
{ a: obj, b: obj },
{ a: obj, b: obj },
];
const entry: logger.LogEntry = {
severity: "ERROR",
message: "testing circular",
a: arr,
b: arr,
};
logger.write(entry);
expectStderr({
severity: "ERROR",
message: "testing circular",
a: [
{ a: { a: "foo" }, b: { a: "foo" } },
{ a: { a: "foo" }, b: { a: "foo" } },
],
b: [
{ a: { a: "foo" }, b: { a: "foo" } },
{ a: { a: "foo" }, b: { a: "foo" } },
],
});
});

it("should not break on objects that override toJSON", () => {
const obj: any = { a: new Date("August 26, 1994 12:24:00Z") };

Expand Down
29 changes: 13 additions & 16 deletions src/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,28 +56,25 @@ function removeCircular(obj: any, refs: any[] = []): any {
if (typeof obj !== "object" || !obj) {
return obj;
}
// If the object defines its own toJSON, prefer that.
if (obj.toJSON) {
// If the object defines its own toJSON method, use it.
if (obj.toJSON && typeof obj.toJSON === "function") {
return obj.toJSON();
}
if (refs.includes(obj)) {
// Only check for circularity among ancestors in the recursion stack.
if (refs.indexOf(obj) !== -1) {
return "[Circular]";
} else {
refs.push(obj);
}
let returnObj: any;
if (Array.isArray(obj)) {
returnObj = new Array(obj.length);
} else {
returnObj = {};
}
for (const k in obj) {
if (refs.includes(obj[k])) {
returnObj[k] = "[Circular]";
} else {
returnObj[k] = removeCircular(obj[k], refs);
// Add the current object to the recursion stack.
refs.push(obj);

const returnObj: any = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
returnObj[key] = removeCircular(obj[key], refs);
}
}
// Remove the current object from the stack once its properties are processed.
refs.pop();
return returnObj;
}

Expand Down
Loading