Skip to content

Commit

Permalink
allow to stringify document circular references
Browse files Browse the repository at this point in the history
  • Loading branch information
maximpn committed May 6, 2024
1 parent e8c1ade commit b0c93da
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
11 changes: 5 additions & 6 deletions packages/kbn-openapi-bundler/src/openapi_bundler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,12 @@ describe('OpenAPI Bundler', () => {
});

describe('circular references', () => {
// Fails because `writeYamlDocument()` has `noRefs: true` setting
// it('bundles recursive spec', async () => {
// const folder = join('circular', 'recursive_spec');
it('bundles recursive spec', async () => {
const folder = join('circular', 'recursive_spec');

// await bundleFolder(folder);
// await expectBundleToMatchFile(DEFAULT_BUNDLED_FILE_PATH, join(folder, 'expected.yaml'));
// });
await bundleFolder(folder);
await expectBundleToMatchFile(DEFAULT_BUNDLED_FILE_PATH, join(folder, 'expected.yaml'));
});

it('bundles specs with recursive references', async () => {
const folder = join('circular', 'circular_ref_specs');
Expand Down
20 changes: 19 additions & 1 deletion packages/kbn-openapi-bundler/src/utils/write_yaml_document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,29 @@ import { dirname } from 'path';

export async function writeYamlDocument(filePath: string, document: unknown): Promise<void> {
try {
const yaml = dump(document, { noRefs: true });
const yaml = stringifyToYaml(document);

await fs.mkdir(dirname(filePath), { recursive: true });
await fs.writeFile(filePath, yaml);
} catch (e) {
throw new Error(`Unable to write bundled yaml: ${e.message}`, { cause: e });
}
}

function stringifyToYaml(document: unknown): string {
try {
// Disable YAML Anchors https://yaml.org/spec/1.2.2/#3222-anchors-and-aliases
// It makes YAML much more human readable
return dump(document, { noRefs: true });
} catch (e) {
// RangeError might happened because of stack overflow
// due to circular references in the document
// since YAML Anchors are disabled
if (e instanceof RangeError) {
// Try to stringify with YAML Anchors enabled
return dump(document, { noRefs: false });
}

throw e;
}
}

0 comments on commit b0c93da

Please sign in to comment.