首頁  >  文章  >  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