UNPKG

json-schema-to-zod

Version:

Converts JSON schema objects or files into Zod schemas

74 lines (73 loc) 2.37 kB
import { withMessage } from "../utils/withMessage.js"; import { parseSchema } from "./parseSchema.js"; export const parseString = (schema) => { let r = "z.string()"; r += withMessage(schema, "format", ({ value }) => { switch (value) { case "email": return [".email(", ")"]; case "ip": return [".ip(", ")"]; case "ipv4": return ['.ip({ version: "v4"', ", message: ", " })"]; case "ipv6": return ['.ip({ version: "v6"', ", message: ", " })"]; case "uri": return [".url(", ")"]; case "uuid": return [".uuid(", ")"]; case "date-time": return [".datetime({ offset: true", ", message: ", " })"]; case "time": return [".time(", ")"]; case "date": return [".date(", ")"]; case "binary": return [".base64(", ")"]; case "duration": return [".duration(", ")"]; } }); r += withMessage(schema, "pattern", ({ json }) => [ `.regex(new RegExp(${json})`, ", ", ")", ]); r += withMessage(schema, "minLength", ({ json }) => [ `.min(${json}`, ", ", ")", ]); r += withMessage(schema, "maxLength", ({ json }) => [ `.max(${json}`, ", ", ")", ]); r += withMessage(schema, "contentEncoding", ({ value }) => { if (value === "base64") { return [".base64(", ")"]; } }); const contentMediaType = withMessage(schema, "contentMediaType", ({ value }) => { if (value === "application/json") { return [ ".transform((str, ctx) => { try { return JSON.parse(str); } catch (err) { ctx.addIssue({ code: \"custom\", message: \"Invalid JSON\" }); }}", ", ", ")" ]; } }); if (contentMediaType != "") { r += contentMediaType; r += withMessage(schema, "contentSchema", ({ value }) => { if (value && value instanceof Object) { return [ `.pipe(${parseSchema(value)}`, ", ", ")" ]; } }); } return r; };