From 634f780ecf864d389dfffd604563d9c1b3e1ee7d Mon Sep 17 00:00:00 2001 From: Tim Novis Date: Thu, 17 Oct 2024 15:17:58 +0100 Subject: [PATCH] Allow for different resource keys than application/json --- src/transform.ts | 12 ++++++++++-- test/fixture/test.yaml | 2 +- test/generate.spec.ts | 2 +- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/transform.ts b/src/transform.ts index 84f1a22..1606f2f 100644 --- a/src/transform.ts +++ b/src/transform.ts @@ -54,7 +54,11 @@ export function transformToGenerateResultFunctions( const useFaker = options?.ai?.enable !== true; if (useFaker) { - const fakerResult = transformJSONSchemaToFakerCode(r.responses?.['application/json']); + if (!r.responses) { + return; + } + const jsonResponseKey = Object.keys(r.responses).filter(r => r.startsWith('application/json'))[0]; + const fakerResult = transformJSONSchemaToFakerCode(r.responses?.[jsonResponseKey]); if (options?.static) { vm.runInContext(`result = ${fakerResult};`, context); } @@ -67,7 +71,11 @@ export function transformToGenerateResultFunctions( ].join('\n'); } - const operationString = JSON.stringify(r.responses?.['application/json'], null, 4); + if (!r.responses) { + return; + } + const jsonResponseKey = Object.keys(r.responses).filter(r => r.startsWith('application/json'))[0]; + const operationString = JSON.stringify(r.responses?.[jsonResponseKey], null, 4); return [ `export async function `, `${name}() { `, diff --git a/test/fixture/test.yaml b/test/fixture/test.yaml index fbe251c..9290863 100644 --- a/test/fixture/test.yaml +++ b/test/fixture/test.yaml @@ -52,7 +52,7 @@ paths: '200': description: OK content: - application/json: + application/json; ; charset=utf-8;: schema: allOf: - $ref: '#/components/schemas/OkResponse' diff --git a/test/generate.spec.ts b/test/generate.spec.ts index 85be673..f3fe647 100644 --- a/test/generate.spec.ts +++ b/test/generate.spec.ts @@ -15,7 +15,7 @@ describe('generate:generateOperationCollection', () => { let schema: OpenAPIV3.SchemaObject; beforeAll(async () => { const collection = await generateCollectionFromSpec('./test/fixture/test.yaml'); - schema = get(collection, [0, 'response', '0', 'responses', 'application/json', 'allOf', 1]); + schema = get(collection, [0, 'response', '0', 'responses', 'application/json; ; charset=utf-8;', 'allOf', 1]); }); it('schema should be defined', () => {