openapi-ts-json-schema
Version:
Generate TypeScript-first JSON schemas from OpenAPI definitions
30 lines (29 loc) • 1 kB
JavaScript
import { stringify as commentJsonStringify } from 'comment-json';
/**
* JSON.stringify replacer
* Replace circular references with {}
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#circular_references
*/
function makeCircularRefReplacer() {
const ancestors = [];
return function (key, value) {
if (typeof value !== 'object' || value === null) {
return value;
}
// `this` is the object that value is contained in,
// i.e., its direct parent.
while (ancestors.length > 0 && ancestors.at(-1) !== this) {
ancestors.pop();
}
// @NOTE Should we make recursion depth configurable?
if (ancestors.includes(value)) {
return {};
}
ancestors.push(value);
return value;
};
}
const circularReplacer = makeCircularRefReplacer();
export function stringify(input) {
return commentJsonStringify(input, circularReplacer, 2);
}