question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add name field to ZodTypeDef

See original GitHub issue

I’ve run into a situation where adding a name field to ZodTypeDef would be very helpful. I have a library that builds OpenAPI specs based on schemas and am having to deal with stack overflows when supporting lazy schemas. I have mostly got around this by tracking visited lazy schemas and creating References on the second time around, the key parts look like this

const visitedLazies = new Set<string>();
function createSchema(
  obj: ReferenceType | Reference<any>,
  components: OpenAPIV3.ComponentsObject,
  keyName?: string,
): OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject | undefined {
  let schemaObject: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject | undefined;

  const def = obj._def;
  if ('typeName' in def) {
    switch (def.typeName) {
      ...
      case z.ZodFirstPartyTypeKind.ZodLazy:
        if (!keyName) { // handle top level lazy schema ie not within an object. should perhaps throw here instead
          schemaObject = createSchema(def.getter(), components);
        } else if (visitedLazies.has(keyName)) {
          schemaObject = { $ref: `#/components/schemas/${keyName}` };
        } else {
          visitedLazies.add(keyName);
          schemaObject = createSchema(def.getter(), components);
          if (schemaObject) {
            components.schemas![keyName] = schemaObject;
          }
        }
        break;
      ...
  }
  return schemaObject;

The problem here is that keyName is the name of the key in an object that contains the lazy. If the schema is z.object({ hello: SomeLazySchema }) then keyName = hello. This is a poor choice because a) the key name is not always the friendliest name to give an OpenAPI component and b) it forces you to make all keys with lazy schemas unique, or you will overwrite them.

I could write a custom zod type that has a name field on it and force lazy schemas to use it. But I’m wondering if this is would be a welcome addition to Zod itself? It’s somewhat similar to adding the description to the schema like https://github.com/colinhacks/zod/commit/e2389b0312fb1b280a90d4bd1f10d099178aec9a.

I’m happy to do the work but wanted to make sure I’m not wasting my time before I do.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:2
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
FlorianWendelborncommented, Mar 27, 2022

@brendo-m unrelated to the issue itself, but in order to solve your main problem of tracking zod schemas, did you try just using the def object itself as a key in a (Weak)Map or as a value in a (Weak)Set? In theory, the object reference itself shouldn’t change, so you can uniquely identify which schema you already processed. Perhaps you don’t need this name proposal due to this?

That being said, I think this issue is still a nice to have feature. But I’d prefer if it was a bit more generic. Why not add a .meta() function that can add any arbitrary metadata to any schema? That sounds like it could be useful for a lot of zod-related third-party libraries that may need to add their own info on the schemas. Similar to what @colinhacks described in description as a JSON string, just less awkward

0reactions
stale[bot]commented, May 26, 2022

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Read more comments on GitHub >

github_iconTop Results From Across the Web

colinhacks/zod: TypeScript-first schema validation ... - GitHub
Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a...
Read more >
Schema validation in TypeScript with Zod - LogRocket Blog
In this article, you will learn about schema design and validation in Zod and how to run it in a TypeScript codebase at...
Read more >
Data validation with automatic typing using zod - CodeX Team
Validating data without pain using the zod library. ... After running this code, we will get an error because the user object is...
Read more >
Zod: create a schema using an existing type - Stack Overflow
Reading your comment it sounds like you want to ensure that your schema is in sync with the Method type from axios.
Read more >
TypeScript schema validation with Zod - Iskander Samatov
Let's create a schema to validate a user object. It will contain the following fields: name; email; phoneNumber. To declare the schema, we...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found