From e325704a0bf23d065a448c84403d854aa81b188a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gast=C3=B3n=20Fournier?= Date: Mon, 6 Mar 2023 12:44:12 +0100 Subject: [PATCH] chore: support for additional media (#3247) ## About the changes Add new methods to simplify the creation of schemas for endpoints with additional media types (other than `application/json`) This is a follow-up on exporting an endpoint as `text/csv` --- .../util/create-response-schema.test.ts | 32 ++++++++++++++- .../openapi/util/create-response-schema.ts | 41 ++++++++++++++----- 2 files changed, 62 insertions(+), 11 deletions(-) diff --git a/src/lib/openapi/util/create-response-schema.test.ts b/src/lib/openapi/util/create-response-schema.test.ts index 45fb51a76a..cc4958a805 100644 --- a/src/lib/openapi/util/create-response-schema.test.ts +++ b/src/lib/openapi/util/create-response-schema.test.ts @@ -1,4 +1,9 @@ -import { createResponseSchema } from './create-response-schema'; +import { + createResponseSchema, + createResponseSchemas, + schemaNamed, + schemaTyped, +} from './create-response-schema'; test('createResponseSchema', () => { expect(createResponseSchema('schemaName')).toMatchInlineSnapshot(` @@ -14,3 +19,28 @@ test('createResponseSchema', () => { } `); }); + +test('createResponseSchemaWithDifferentMedia', () => { + expect( + createResponseSchemas('my-schema', { + 'application/json': schemaNamed('schemaName'), + 'text/css': schemaTyped('string'), + }), + ).toMatchInlineSnapshot(` + { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/schemaName", + }, + }, + "text/css": { + "schema": { + "type": "string", + }, + }, + }, + "description": "my-schema", + } + `); +}); diff --git a/src/lib/openapi/util/create-response-schema.ts b/src/lib/openapi/util/create-response-schema.ts index d2d58f6341..73e4e43d75 100644 --- a/src/lib/openapi/util/create-response-schema.ts +++ b/src/lib/openapi/util/create-response-schema.ts @@ -1,18 +1,39 @@ import { OpenAPIV3 } from 'openapi-types'; +export const createResponseSchemas = ( + description: string, + content: { [media: string]: OpenAPIV3.MediaTypeObject }, +): OpenAPIV3.ResponseObject => { + return { + description, + content: content, + }; +}; + +export const schemaNamed = (schemaName: string): OpenAPIV3.MediaTypeObject => { + return { + schema: { + $ref: `#/components/schemas/${schemaName}`, + }, + }; +}; + +export const schemaTyped = ( + type: OpenAPIV3.NonArraySchemaObjectType, +): OpenAPIV3.MediaTypeObject => { + return { + schema: { + type, + }, + }; +}; + export const createResponseSchema = ( schemaName: string, ): OpenAPIV3.ResponseObject => { - return { - description: schemaName, - content: { - 'application/json': { - schema: { - $ref: `#/components/schemas/${schemaName}`, - }, - }, - }, - }; + return createResponseSchemas(schemaName, { + 'application/json': schemaNamed(schemaName), + }); }; export const resourceCreatedResponseSchema = (