Валидация форм с помощью библиотеки zod

env.js
import { z } from 'zod';
 
const EnvSchema = z.object({
  DATABASE_URL: z.string({
      description: 'CosmosDB Connection string',
      required_error: '😱 You forgot to add a database URL',
    })
    .url()
    .min(3),
  NODE_ENV: z.enum(
    [
      'development',
      'test',
      'production',
    ],
    {
      description: 'This gets updated depending on your environment',
    }
  ).default('development'),
  PORT: z.coerce
    .number({
      description: '.env files convert numbers to strings, therefoore we have to enforce them to be numbers',
    })
    .positive()
    .max(65536, `options.port should be >= 0 and < 65536`)
    .default(3000),
});
 
export const env = EnvSchema.parse(process.env);

Теперь можно использовать exports

main.js
import { env } from './env.js';
 
console.log(`Selected port is ${env.PORT}`);
  • works/programmer/js/zod-object-validation.txt
  • Последнее изменение: 2025/02/23 17:50
  • Eugene