Skip to content
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

Some additional utilities #2

Open
2 of 5 tasks
jamesarosen opened this issue Mar 10, 2023 · 1 comment
Open
2 of 5 tasks

Some additional utilities #2

jamesarosen opened this issue Mar 10, 2023 · 1 comment

Comments

@jamesarosen
Copy link
Contributor

jamesarosen commented Mar 10, 2023

There are some utilities I use locally for which I'm looking for a home. I'm happy to contribute them here or -- if you prefer -- create my own zod-contrib package.

  • timestamp.{ms,s}: z.numbers that are branded as a Timestamp<ms> and Timestamp<s> respectively to avoid confusion with other units. Sane defaults for min and max to ensure users don't try to parse ms as s and vice versa
  • color.{hex,hsl,hsla,lch,rgb,rgba}: branded z.strings, plus a color that's a union of them
  • response: validate status, headers of a Response; chains for parsing text or json body (requires parseAsync)
  • jsonSchema: the JSON type from the zod README
  • jsonString: a z.string that does a refining transform to a JSON object (input: string, output: jsonSchema); great for piping into other schemas

The end result is something you can use to validate & type responses from a CMS:

const article = z.object({
  lastUpdated: zu.timestamp.ms(),
  title: z.string(),
  titleColor: zu.color().optional(),
})

const articleResponse = z.pipeline(
  zu.response({ status: 200 }).json(),
  zu.jsonString(),
  z.object({ article }),
)
 
const myArticle = await articleResponse.parseAsync(await fetch('/articles/123'))

Would any of this be a good fit here?

@JacobWeisenburger
Copy link
Owner

These all sound good. Please make PRs, so I can see more details.

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

2 participants