Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed AxiosError.toJSON method to avoid circular references; #5247

Merged
merged 3 commits into from Nov 22, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/core/AxiosError.js
Expand Up @@ -45,7 +45,7 @@ utils.inherits(AxiosError, Error, {
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
config: utils.toJSONObject(this.config),
code: this.code,
status: this.response && this.response.status ? this.response.status : null
};
Expand Down
34 changes: 33 additions & 1 deletion lib/utils.js
Expand Up @@ -592,6 +592,37 @@ const toFiniteNumber = (value, defaultValue) => {
return Number.isFinite(value) ? value : defaultValue;
}

const toJSONObject = (obj) => {
const stack = new Array(10);

const visit = (source, i) => {

if (isObject(source)) {
if (stack.indexOf(source) >= 0) {
return;
}

if(!('toJSON' in source)) {
stack[i] = source;
const target = isArray(source) ? [] : {};

forEach(source, (value, key) => {
const reducedValue = visit(value, i + 1);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});

stack[i] = undefined;

return target;
}
}

return source;
}

return visit(obj, 0);
}

export default {
isArray,
isArrayBuffer,
Expand Down Expand Up @@ -637,5 +668,6 @@ export default {
toFiniteNumber,
findKey,
global: _global,
isContextDefined
isContextDefined,
toJSONObject
};
26 changes: 26 additions & 0 deletions test/unit/utils/utils.js
Expand Up @@ -23,4 +23,30 @@ describe('utils', function (){
assert.equal(utils.isFormData(new FormData()), true);
});
});

describe('toJSON', function (){
it('should convert to a plain object without circular references', function () {
const obj= {a: [0]}
const source = {x:1, y:2, obj};
source.circular1 = source;
obj.a[1] = obj;

assert.deepStrictEqual(utils.toJSONObject(source), {
x: 1, y:2, obj: {a: [0]}
});
});

it('should use objects with defined toJSON method without rebuilding', function () {
const objProp = {};
const obj= {objProp, toJSON(){
return {ok: 1}
}};
const source = {x:1, y:2, obj};

const jsonObject = utils.toJSONObject(source);

assert.strictEqual(jsonObject.obj.objProp, objProp);
assert.strictEqual(JSON.stringify(jsonObject), JSON.stringify({x: 1, y:2, obj: {ok: 1}}))
});
});
});