首页  >  文章  >  web前端  >  使用 Zod 验证您的环境变量

使用 Zod 验证您的环境变量

WBOY
WBOY原创
2024-08-16 12:40:06843浏览

Validate your environment variables with Zod

Zod 是 TypeScript 生态系统中最著名的验证库。使用 Zod,您可以创建一个 模式 并根据该模式验证您的数据。观察下面的架构:

import { z } from 'zod'

const UserSchema = z.object({
  name: z.string().min(1),
  age: z.number({ coerce: true }).min(18),
  email: z.string().email(),
})

此模式可用于验证对象,如下所示:

const data = {
  name: 'John Doe',
  age: 18,
  email: 'john@example.com',
}

// If there is a validation error, it throws an error
const validatedData = UserSchema.parse(data)

// If there is a validation error, it returns an error object for you to handle later
const safeValidatedData = UserSchema.safeParse(data)
// => { success: false; error: ZodError }
// => { success: true; data: 'billie' }

Zod 能够对您的数据执行各种类型的验证,因此请务必阅读文档以了解更多详细信息。

验证环境变量

我们可以使用 Zod 来验证 process.env 中存在的值,甚至可以在应用程序中使用环境变量之前处理它们。通常,我喜欢创建一个environment.ts文件,如下例所示:

import { z } from 'zod'

const environmentSchema = z.object({
  // Define the possible values for NODE_ENV, always leaving a default value:
  NODE_ENV: z.enum(['test', 'development', 'production']).default('production'),
  // Environment variables are always defined as strings. Here, convert the string to a number and set a default value:
  PORT: z.number({ coerce: true }).default(3000),
})

export const env = environmentSchema.parse(process.env)

然后,只需导入变量并在我的应用程序中使用它:

import Fastify from 'fastify'
import { env } from './environment.js'

const app = Fastify({ logger: true })
app.listen({ port: env.PORT }, (err) => {
  if (err) {
    app.log.error(err)
    process.exit(1)
  }
})

以上是使用 Zod 验证您的环境变量的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn