当然, 我可以为您提供在 Bun 环境下使用 Zod 的一些案例。Zod 是一个 TypeScript 优先的模式声明和验证库, 非常适合用于数据验证、API 请求/响应验证等场景。以下是一些在 Bun 中使用 Zod 的示例:

首先, 确保您已经安装了 Zod:

bun add zod
  1. 基本使用
import { z } from "zod";
 
// 定义一个简单的模式
const UserSchema = z.object({
  name: z.string(),
  age: z.number().min(0).max(120),
  email: z.string().email(),
});
 
// 使用模式验证数据
try {
  const user = UserSchema.parse({
    name: "John Doe",
    age: 30,
    email: "john@example.com",
  });
  console.log("Valid user:", user);
} catch (error) {
  console.error("Validation error:", error);
}
  1. 自定义错误消息
const CustomUserSchema = z.object({
  name: z.string().min(2, { message: "Name must be at least 2 characters long" }),
  age: z.number().min(18, { message: "Must be at least 18 years old" }),
  email: z.string().email({ message: "Invalid email address" }),
});
 
try {
  CustomUserSchema.parse({
    name: "J",
    age: 16,
    email: "invalid-email",
  });
} catch (error) {
  if (error instanceof z.ZodError) {
    console.error("Validation errors:", error.errors);
  }
}
  1. 嵌套对象和数组
const AddressSchema = z.object({
  street: z.string(),
  city: z.string(),
  zipCode: z.string(),
});
 
const UserWithAddressSchema = z.object({
  name: z.string(),
  addresses: z.array(AddressSchema).nonempty(),
});
 
const user = UserWithAddressSchema.parse({
  name: "Alice",
  addresses: [
    { street: "123 Main St", city: "Anytown", zipCode: "12345" },
    { street: "456 Elm St", city: "Othertown", zipCode: "67890" },
  ],
});
 
console.log("Valid user with addresses:", user);
  1. 联合类型和可选字段
const ResponseSchema = z.object({
  status: z.union([z.literal("success"), z.literal("error")]),
  data: z.object({
    id: z.number(),
    name: z.string(),
  }).optional(),
  error: z.string().optional(),
});
 
const successResponse = ResponseSchema.parse({
  status: "success",
  data: { id: 1, name: "John" },
});
 
const errorResponse = ResponseSchema.parse({
  status: "error",
  error: "Not found",
});
 
console.log("Success response:", successResponse);
console.log("Error response:", errorResponse);
  1. 与 Bun 的 Fetch API 结合使用
import { z } from "zod";
 
const TodoSchema = z.object({
  userId: z.number(),
  id: z.number(),
  title: z.string(),
  completed: z.boolean(),
});
 
async function fetchTodo(id: number) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
  const data = await response.json();
  return TodoSchema.parse(data);
}
 
try {
  const todo = await fetchTodo(1);
  console.log("Fetched and validated todo:", todo);
} catch (error) {
  if (error instanceof z.ZodError) {
    console.error("Validation error:", error.errors);
  } else {
    console.error("Fetch error:", error);
  }
}
  1. 使用 Zod 生成 TypeScript 类型
import { z } from "zod";
 
const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
  role: z.enum(["admin", "user", "guest"]),
});
 
// 从Zod模式生成TypeScript类型
type User = z.infer<typeof UserSchema>;
 
// 使用生成的类型
function processUser(user: User) {
  console.log(`Processing user: ${user.name} (${user.role})`);
}
 
const validUser: User = {
  id: 1,
  name: "Alice",
  email: "alice@example.com",
  role: "admin",
};
 
processUser(validUser);
  1. 在 Bun 的 HTTP 服务器中使用 Zod 进行请求验证
import { serve } from "bun";
import { z } from "zod";
 
const CreateUserSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
  age: z.number().min(18).optional(),
});
 
const server = serve({
  port: 3000,
  async fetch(req) {
    if (req.method === "POST" && new URL(req.url).pathname === "/users") {
      try {
        const body = await req.json();
        const validatedUser = CreateUserSchema.parse(body);
        // 处理验证后的用户数据...
        return new Response(JSON.stringify({ success: true, user: validatedUser }), {
          headers: { "Content-Type": "application/json" },
        });
      } catch (error) {
        if (error instanceof z.ZodError) {
          return new Response(JSON.stringify({ success: false, errors: error.errors }), {
            status: 400,
            headers: { "Content-Type": "application/json" },
          });
        }
      }
    }
    return new Response("Not Found", { status: 404 });
  },
});
 
console.log(`Server running at http://localhost:${server.port}`);

这些例子展示了如何在 Bun 环境中使用 Zod 进行各种数据验证和类型推断。Zod 的强大之处在于它可以轻松地定义复杂的数据结构, 并提供运行时验证。在 Bun 的高性能环境中, Zod 可以帮助您构建更加健壮和类型安全的应用程序。