netzo / fresh-netzo

Full-stack Deno Fresh meta-framework for building business web apps like internal tools, dashboards, admin panels and automated workflows.
https://netzo.io
MIT License
52 stars 2 forks source link

[zod] allow loading serialized zod schemas (e.g. from DB) #79

Closed miguelrk closed 7 months ago

miguelrk commented 8 months ago

Add following utility function using json-schema-to-zod to netzo/core/utils/database.utils.ts:

import { z } from "netzo/deps/zod/mod.ts";

const createZodSchema = (schema: string) => {
  return (new Function('z', `return ${schema};`))(z);
}

So that it can be used as follows e.g. for a user schema:

import { jsonSchemaToZod } from "npm:json-schema-to-zod@2.0.14";

const userJsonSchema = {
  "type": "object",
  "properties": {
    "id": { "type": "string" },
    "name": { "type": "string" },
  },
  "required": ["id", "name"]
}

export const userSchema = createZodSchema(userJsonSchema, z)

export type User = z.infer<typeof userSchema>;

Alternativeley, we could also use ajv-ts (see issue 31 of @vitalics/ajv-ts)

miguelrk commented 7 months ago

Closing as not relevant (at least for now)