From 3d0e07f22a5dcf33d80ce33c2bcb2745b09f84a3 Mon Sep 17 00:00:00 2001 From: Abraxas-365 Date: Tue, 10 Sep 2024 23:25:28 -0500 Subject: [PATCH] fix: swagger date time --- bun.lockb | Bin 373135 -> 373135 bytes src/swagger/index.ts | 71 ++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/bun.lockb b/bun.lockb index 6ebdda90d5a07b3b3c6b7a6375bddd3514979631..a5473bc1fe2af444638b18245cc68d6e6c2333f9 100755 GIT binary patch delta 30 mcmeBwEY|;6tf7Umg=q`(`<>JERarROf9z!5{$nT0^zQ)CC=Mt9 delta 33 mcmeBwEY|;6tf7Umg=q`(`9!VNb7 diff --git a/src/swagger/index.ts b/src/swagger/index.ts index 062556f..60a0144 100644 --- a/src/swagger/index.ts +++ b/src/swagger/index.ts @@ -1,4 +1,52 @@ -import type { OpenAPIV3 } from 'openapi-types' +import { OpenAPIV3 } from 'openapi-types'; + +type DateTimeSchema = { + type: 'string'; + format: 'date-time'; + default?: string; +}; + +type SchemaObject = OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject; + +function isSchemaObject(schema: SchemaObject): schema is OpenAPIV3.SchemaObject { + return 'type' in schema || 'properties' in schema || 'items' in schema; +} + +function isDateTimeProperty(key: string, schema: OpenAPIV3.SchemaObject): boolean { + return (key === 'createdAt' || key === 'updatedAt') && + 'anyOf' in schema && + Array.isArray(schema.anyOf); +} + +function transformDateProperties(schema: SchemaObject): SchemaObject { + if (!isSchemaObject(schema) || typeof schema !== 'object' || schema === null) { + return schema; + } + + const newSchema: OpenAPIV3.SchemaObject = { ...schema }; + + Object.entries(newSchema).forEach(([key, value]) => { + if (isSchemaObject(value)) { + if (isDateTimeProperty(key, value)) { + const dateTimeFormat = value.anyOf?.find((item): item is OpenAPIV3.SchemaObject => + isSchemaObject(item) && item.format === 'date-time' + ); + if (dateTimeFormat) { + const dateTimeSchema: DateTimeSchema = { + type: 'string', + format: 'date-time', + default: dateTimeFormat.default + }; + (newSchema as Record)[key] = dateTimeSchema; + } + } else { + (newSchema as Record)[key] = transformDateProperties(value); + } + } + }); + + return newSchema; +} export const SwaggerUIRender = ( info: OpenAPIV3.InfoObject, @@ -11,7 +59,21 @@ export const SwaggerUIRender = ( }, stringifiedSwaggerOptions: string, autoDarkMode?: boolean -) => ` +): string => { + const swaggerOptions: OpenAPIV3.Document = JSON.parse(stringifiedSwaggerOptions); + + if (swaggerOptions.components && swaggerOptions.components.schemas) { + swaggerOptions.components.schemas = Object.fromEntries( + Object.entries(swaggerOptions.components.schemas).map(([key, schema]) => [ + key, + transformDateProperties(schema) + ]) + ); + } + + const transformedStringifiedSwaggerOptions = JSON.stringify(swaggerOptions); + + return ` @@ -57,8 +119,9 @@ export const SwaggerUIRender = ( -` +`; +};