UNPKG

@cabloy/zod-openapi

Version:
55 lines (54 loc) 1.79 kB
import { isZodType, Metadata } from '@cabloy/zod-to-openapi'; export class ZodMetadata { static unwrapUntil(schema, typeName) { return Metadata.unwrapUntil(schema, typeName); } static unwrapChained(schema) { if (!schema) return undefined; return Metadata.unwrapChained(schema); } static getDefaultValue(zodSchema) { return Metadata.getDefaultValue(zodSchema); } static getInternalMetadata(zodSchema) { return Metadata.getInternalMetadata(zodSchema); } static getLazySchema(zodSchema) { const innerSchema = this.unwrapChained(zodSchema); return zodSchema._zod.def.getter ?? innerSchema._zod.def.getter; } static resolveLazySchema(zodSchema) { const getter = this.getLazySchema(zodSchema); if (!getter) return zodSchema; // metadata: first const metadata = this.getOpenapiMetadata(zodSchema); zodSchema = getter(); return metadata ? zodSchema.openapi(metadata) : zodSchema; } static getRefId(zodSchema) { return Metadata.getRefId(zodSchema); } static getFieldSchema(zodSchema, key) { if (!zodSchema) return; let schema; if (zodSchema.def.type === 'object') { schema = zodSchema; } else if (zodSchema.def.type === 'union') { schema = zodSchema.def.options.find(item => item.def.type === 'object'); } else { throw new Error('invalid zod schema'); } return schema.shape[key]; } static getOpenapiMetadata(zodSchema) { return Metadata.getOpenApiMetadata(zodSchema); } static isZodType(schema, typeNames) { return isZodType(schema, typeNames); } }