Skip to content

Commit

Permalink
feat: add inline comment on circular ref resolution truncation (#179)
Browse files Browse the repository at this point in the history
  • Loading branch information
toomuchdesign authored Feb 21, 2024
1 parent 1f01e99 commit 62d3d9d
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/utils/makeTsJsonSchema/getCircularReplacer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { REF_SYMBOL } from '../';

/**
* JSON.stringify replacer
* Replace circular references with {}
Expand All @@ -21,7 +23,17 @@ export function getCircularReplacer(): (

// @NOTE Should we make recursion depth configurable?
if (ancestors.includes(value)) {
return {};
// @ts-expect-error REF_SYMBOL doesn't exist on value
const ref = value[REF_SYMBOL];
return {
// Drop an inline comment about recursion interruption
[Symbol.for('before')]: [
{
type: 'LineComment',
value: ` Circular recursion interrupted (${ref})`,
},
],
};
}

ancestors.push(value);
Expand Down
25 changes: 25 additions & 0 deletions test/circularReference.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'path';
import { describe, it, expect } from 'vitest';
import fs from 'fs/promises';
import { fixtures, makeTestOutputPath } from './test-utils';
import { openapiToTsJsonSchema } from '../src';

Expand All @@ -22,6 +23,7 @@ describe('Circular reference', () => {
path.resolve(outputPath, 'components/schemas/January')
);

// Parsed schema expectations
expect(januarySchema.default).toEqual({
description: 'January description',
type: 'object',
Expand Down Expand Up @@ -49,6 +51,29 @@ describe('Circular reference', () => {
},
},
});

// Inline comments expectations
const februarySchemaAsText = await fs.readFile(
path.resolve(outputPath, 'components/schemas/February.ts'),
{
encoding: 'utf8',
},
);

const expectedInlinedRef = `
nextMonth: {
// Circular recursion interrupted (#/components/schemas/February)
},
nextMonthTwo: {
// Circular recursion interrupted (#/components/schemas/February)
},
nextMonthThree: {
// Circular recursion interrupted (#/components/schemas/February)
},`;

expect(februarySchemaAsText).toEqual(
expect.stringContaining(expectedInlinedRef),
);
});
});

Expand Down
2 changes: 1 addition & 1 deletion test/refHandling-inline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe('refHandling option === "inline"', () => {
},
);

const expectedInlinedRef = await `
const expectedInlinedRef = `
properties: {
isJanuary: {
// $ref: "#/components/schemas/Answer"
Expand Down

0 comments on commit 62d3d9d

Please sign in to comment.