8000 Metadata registries don't solve some problems I've used metadata for · Issue #4319 · colinhacks/zod · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Metadata registries don't solve some problems I've used metadata for #4319

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jedwards1211 opened this issue May 5, 2025 · 0 comments
Open

Comments

@jedwards1211
Copy link
jedwards1211 commented May 5, 2025

The best example is declaring "versioned" schemas I can use to support different versions of a JSON file format.

Here's a basic example of a schema for a file format with two versions, where in version 2 the dataType property gets renamed to type:

const MetadataItem = z.object({
  tag: z.string(),
  // version(schema, metadata) wraps a schema with the given metadata
  dataType: version(z.enum(['number', 'string', 'boolean']), { until: 2 }),
  type: version(z.enum(['number', 'string', 'boolean']), { since: 2 }),
})

// now we want a schemaForVersion(schema, version) function such that:

const MetadataItemV1 = schemaForVersion(MetadataItem, 1) // somehow magically lacks the `type` property
type MetadataItemV1 = z.infer<typeof MetadataItemV1> // also somehow magically lacks the `type` property

const MetadataItemV2 = schemaForVersion(MetadataItem, 2) // somehow magically lacks the `dataType` property
type MetadataItemV2 = z.infer<typeof MetadataItemV2> // also somehow magically lacks the `dataType` property

// Now we can write a typesafe function to normalize old versions to the latest version

Before coming up with this approach I had separate Zod schemas for each version of the file and code to convert between each, but my coworkers complained that this was too tedious and they wanted to be able to only have one declaration of a given property that can be shared across versions (until it's renamed, moved, or removed in a breaking change in a new file version).

I needed to be able to build accurate TS types for each file version from this base schema to be confident about how well our code that normalizes to the latest version is type checked.

Doing something like this is only possible when Zod schemas anywhere in the tree can be wrapped with something that contains custom type information (in this case, the until/since metadata at type time).

Here's the full article about the approach I came up with: https://www.jcore.io/articles/schema-versioning-with-zod

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant
0