MCPcopy Create free account
hub / github.com/FlowiseAI/Flowise / createZodSchemaFromJSON

Function createZodSchemaFromJSON

packages/components/src/utils.ts:2180–2274  ·  view source on GitHub ↗
(jsonSchema: any)

Source from the content-addressed store, hash-verified

2178 * @returns {z.ZodTypeAny} - A Zod schema
2179 */
2180export const createZodSchemaFromJSON = (jsonSchema: any): z.ZodTypeAny => {
2181 // If the schema is an object with properties, create an object schema
2182 if (typeof jsonSchema === 'object' && jsonSchema !== null) {
2183 const schemaObj: Record<string, z.ZodTypeAny> = {}
2184
2185 // Process each property in the schema
2186 for (const [key, value] of Object.entries(jsonSchema)) {
2187 if (value === null) {
2188 // Handle null values
2189 schemaObj[key] = z.null()
2190 } else if (typeof value === 'object' && !Array.isArray(value)) {
2191 // Check if the property has a type definition
2192 if ('type' in value) {
2193 const type = value.type as string
2194 const description = ('description' in value ? (value.description as string) : '') || ''
2195
2196 // Create the appropriate Zod type based on the type property
2197 if (type === 'string') {
2198 schemaObj[key] = z.string().describe(description)
2199 } else if (type === 'number') {
2200 schemaObj[key] = z.number().describe(description)
2201 } else if (type === 'boolean') {
2202 schemaObj[key] = z.boolean().describe(description)
2203 } else if (type === 'array') {
2204 // If it's an array type, check if items is defined
2205 if ('items' in value && value.items) {
2206 const itemSchema = createZodSchemaFromJSON(value.items)
2207 schemaObj[key] = z.array(itemSchema).describe(description)
2208 } else {
2209 // Default to array of any if items not specified
2210 schemaObj[key] = z.array(z.any()).describe(description)
2211 }
2212 } else if (type === 'object') {
2213 // If it's an object type, check if properties is defined
2214 if ('properties' in value && value.properties) {
2215 const nestedSchema = createZodSchemaFromJSON(value.properties)
2216 schemaObj[key] = nestedSchema.describe(description)
2217 } else {
2218 // Default to record of any if properties not specified
2219 schemaObj[key] = z.record(z.any()).describe(description)
2220 }
2221 } else {
2222 // Default to any for unknown types
2223 schemaObj[key] = z.any().describe(description)
2224 }
2225
2226 // Check if the property is optional
2227 if ('optional' in value && value.optional === true) {
2228 schemaObj[key] = schemaObj[key].optional()
2229 }
2230 } else if (Array.isArray(value)) {
2231 // Array values without a type property
2232 if (value.length > 0) {
2233 // If the array has items, recursively create a schema for the first item
2234 const itemSchema = createZodSchemaFromJSON(value[0])
2235 schemaObj[key] = z.array(itemSchema)
2236 } else {
2237 // Empty array, allow any array

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected