|

7 Powerful Use Cases for Zod Schemas | by Mike Chen

Build in AI speed — Compose enterprise-grade applications, features, and components

import { z } from ‘zod’;
import { useForm } from ‘react-hook-form’;
import { zodResolver } from ‘@hookform/resolvers/zod’;

const UserSchema = z.object({
name: z.string().min(2, “Name must be at least 2 characters”),
email: z.string().email(“Invalid email address”),
age: z.number().min(18, “You must be at least 18 years old”),
});

const { register, handleSubmit, formState: { errors } } = useForm({
resolver: zodResolver(UserSchema),
});

const BookSchema = z.object({
id: z.number(),
author: z.string(),
});

async function fetchUser() {
const response = await fetch(“https://api.example.com/book/28292827”);
const data = await response.json();
const parsedData = BookSchema.parse(data);
return parsedData;
}

See Also  An Ode To Side Project Time — Smashing Magazine

const BlogMetadata = z.object({
id: z.number(),
title: z.string(),
author: z.string(),
modified: z.string().datetime(),
});

import { z } from ‘zod’;
import { Fixture } from ‘zod-fixture’;

const PersonSchema = z.object({
name: z.string(),
birthday: z.date(),
address: z.object({
street: z.string(),
city: z.string(),
state: z.string(),
}),
pets: z.array(z.object({ name: z.string(), breed: z.string() })),
totalVisits: z.number().int(),
});

const fixture = new Fixture();
const person = fixture.fromSchema(PersonSchema);

console.log(person);
// {
// name: ‘barmftzlcngaynw’,
// birthday: 2089-04-19T20:26:28.411Z,
// address: {
// street: ‘wyttcnyvxpetrsa’,
// city: ‘d-iveauywljfifd’,
// state: ‘cetuqnbvmbkqwlt’
// },
// pets: [
// { name: ‘bonzm-sjnglvkbb’, breed: ‘fbmiabahyvsy-vm’ },
// { name: ‘wqbjuehl-trb-ai’, breed: ‘vifsztjznktjkve’ },
// { name: ‘brrvbrgzmjhttzh’, breed: ‘cq-jcmhccaduqmk’ }
// ],
// totalVisits: 24
// }

import { z } from ‘zod’;

export const blogContentSchema = z.object({
seoDescription: z
.string()
.describe(
‘The SEO-optimized description of the blog post (150-160 characters).’
),
seoTitle: z.string().describe(‘The SEO-optimized title of the blog post.’),
keywords: z
.array(z.string().describe(‘A keyword or category for the blog.’))
.describe(‘An array of keywords or categories for the blog.’),
content: z
.string()
.describe(‘The main content of the blog in markdown format.’),
});

const llm = new ChatOpenAI();

const structuredLLM = llm.withStructuredOutput(blogContentSchema);

// …

{
“seoDescription”:”Explore use cases of Zod schemas”
“seoTitle”:”Advanced Zod Schema Use Cases in TypeScript”,
“keywords”:[“Zod schema”,”TypeScript”,”data validation”,”schema validation”],
“content”:”# Zod Schema Use Cases…”
}

See Also  OTP Authentication in Laravel & Vue.js for Secure Transactions

import { z } from ‘zod’;

const BlogSchema = z.object({
id: z.number(),
title: z.string(),
author: z.string(),
labels: z.array(z.string()).transform((labels) => new Set(labels)),
});

const blogData = BlogSchema.parse({
id: 1,
title: ‘Hello World’,
author: ‘John Doe’,
labels: [‘foo’, ‘bar’, ‘foo’],
});

console.log(blogData);

// {
// id: 1,
// title: ‘Hello World’,
// author: ‘John Doe’,
// labels: Set(2) { ‘foo’, ‘bar’ }
// }

import { z } from “zod”;

const argsSchema = z.object({
port: z.string().regex(/^\d+$/, “Port must be a number”).transform(Number),
mode: z.enum([“development”, “production”]),
});

const rawArgs = { port: “3000”, mode: “development” };

const parsedArgs = argsSchema.parse(rawArgs);

Source link

Similar Posts