fastify-type-provider-zod
Version:
Zod Type Provider for Fastify@5
66 lines (65 loc) • 1.64 kB
JavaScript
import { z } from "zod/v4";
const getSchemaId = (id, io) => {
return io === "input" ? `${id}Input` : id;
};
const getReferenceUri = (id, io) => {
return `#/components/schemas/${getSchemaId(id, io)}`;
};
function isZodDate(entity) {
return entity.constructor.name === "ZodDate";
}
const getOverride = (ctx, io) => {
if (io === "output") {
if (isZodDate(ctx.zodSchema)) {
ctx.jsonSchema.type = "string";
ctx.jsonSchema.format = "date-time";
}
}
};
const deleteInvalidProperties = (schema) => {
const object = { ...schema };
delete object.id;
delete object.$schema;
return object;
};
const zodSchemaToJson = (zodSchema, registry, io) => {
const result = z.toJSONSchema(zodSchema, {
io,
unrepresentable: "any",
cycles: "ref",
reused: "inline",
external: {
registry,
uri: (id) => getReferenceUri(id, io),
defs: {}
},
override: (ctx) => getOverride(ctx, io)
});
const jsonSchema = deleteInvalidProperties(result);
return jsonSchema;
};
const zodRegistryToJson = (registry, io) => {
const result = z.toJSONSchema(registry, {
io,
unrepresentable: "any",
cycles: "ref",
reused: "inline",
uri: (id) => getReferenceUri(id, io),
external: {
registry,
uri: (id) => getReferenceUri(id, io),
defs: {}
},
override: (ctx) => getOverride(ctx, io)
}).schemas;
const jsonSchemas = {};
for (const id in result) {
jsonSchemas[getSchemaId(id, io)] = deleteInvalidProperties(result[id]);
}
return jsonSchemas;
};
export {
zodRegistryToJson,
zodSchemaToJson
};
//# sourceMappingURL=zod-to-json.js.map