zoxy 中文文档教程

发布于 2年前 浏览 19 项目主页 更新于 2年前

围绕 Zod 的小型类型安全对象代理,可帮助您在加载数据后保持安全。

因为在加载复杂结构后对其进行深入修改和验证可能有点冗长。

如果加载后不需要修改数据,则可能不需要 zoxy!


Installation

pnpm add zod zoxy

Basic usage (live demo)

import { z } from 'zod';
import { zoxy } from 'zoxy';

const User = z.object({
  username: z.string().min(4),
  email: z.string().email().optional(),
  phone: z.object({
    home: z.string().min(10).max(42).optional(),
    work: z.string().min(10).max(42).optional(),
  }),
  foo: z.object({ bar: z.object({ baz: z.string().max(3).optional() }).optional() }).optional(),
});

const user = zoxy(User, { username: 'anonymous', phone: {} });

// Pass
user.username = 'nyan';
user.email = undefined;
user.phone.home = '555 042 42 42';
user.phone = { home: '555 042 42 42', work: '555 024 24 24' };

// Fail
user.email = 'xxx'; // throw 'Invalid email'
user.phone = { home: 'xxx' }; // throw 'String must contain at least 10 character(s)'

Ensure default value

In the example below the模式具有三个级别,这些级别都是可选的,如果您想定义最后一个级别,它可能会非常冗长。 Zoxy 提供了一个解决方案,带有一个小助手,可确保设置默认值。只需在所需值前加上“$”符号前缀,您就可以获得一个允许您设置默认值的方法。

const Data = z.object({
  foo: z
    .object({
      bar: z
        .object({
          baz: z.string().max(3).optional(),
        })
        .optional(),
    })
    .optional(),
});

const data = zoxy(Data, {});

// Get `data.foo.bar.baz` if defined or set default value where needed.
const baz = data.$foo({}).$bar({}).$baz('baz'); // 'baz'

上述行将执行以下操作:

  • 如果 data.foo 未定义,则将其设置为 {}
  • 如果 data.foo.bar 未定义,则将其设置为 {}
  • 如果 data.foo.bar.baz 未定义,将其设置为 'baz'
  • 返回 data.foo.bar.baz

请注意,如果之前已经初始化过,则返回值可能与默认值不同。

设置深度可选属性

如果要深度分配新值,则必须使用以下语法。

// Set default value on `foo.bar` where needed and set `foo.bar.baz` to 'buzz'.
data.$foo({}).$bar({}).baz = 'buzz';

console.log(data.foo?.bar?.baz); // 'buzz'

签名

function zoxy(schema: ZodObject, data: Data, options?: ZoxyOptions): Zoxy;

选项

type ZoxyOptions = {
  prefix: string; // default '$'
};

使用 @skarab/skaffold 搭建的

A small type-safe object proxy around Zod to help you stay safe after your data is loaded.

Because it can be a bit verbose to modify and validate complex structures deeply after loading them.

If you don't need to modify your data after loading, you probably don't need zoxy!


Installation

pnpm add zod zoxy

Basic usage (live demo)

import { z } from 'zod';
import { zoxy } from 'zoxy';

const User = z.object({
  username: z.string().min(4),
  email: z.string().email().optional(),
  phone: z.object({
    home: z.string().min(10).max(42).optional(),
    work: z.string().min(10).max(42).optional(),
  }),
  foo: z.object({ bar: z.object({ baz: z.string().max(3).optional() }).optional() }).optional(),
});

const user = zoxy(User, { username: 'anonymous', phone: {} });

// Pass
user.username = 'nyan';
user.email = undefined;
user.phone.home = '555 042 42 42';
user.phone = { home: '555 042 42 42', work: '555 024 24 24' };

// Fail
user.email = 'xxx'; // throw 'Invalid email'
user.phone = { home: 'xxx' }; // throw 'String must contain at least 10 character(s)'

Ensure default value

In the example below the schema has three levels which are all optional and if you want to define the last level it can be quite verbose. Zoxy offers a solution to this with a little helper that makes sure that a default value is set. Simply prefix the desired value with a '$' sign and you get a method that allows you to set a default value.

const Data = z.object({
  foo: z
    .object({
      bar: z
        .object({
          baz: z.string().max(3).optional(),
        })
        .optional(),
    })
    .optional(),
});

const data = zoxy(Data, {});

// Get `data.foo.bar.baz` if defined or set default value where needed.
const baz = data.$foo({}).$bar({}).$baz('baz'); // 'baz'

The above line will perform the following actions:

  • if data.foo is undefined set it to {}
  • if data.foo.bar is undefined set it to {}
  • if data.foo.bar.baz is undefined set it to 'baz'
  • return data.foo.bar.baz

Note that the returned value can be something different from the default value if it has already been initialized previously.

Set deep optional property

If you want to assign a new value deeply you must use the following syntax.

// Set default value on `foo.bar` where needed and set `foo.bar.baz` to 'buzz'.
data.$foo({}).$bar({}).baz = 'buzz';

console.log(data.foo?.bar?.baz); // 'buzz'

Signature

function zoxy(schema: ZodObject, data: Data, options?: ZoxyOptions): Zoxy;

Options

type ZoxyOptions = {
  prefix: string; // default '$'
};

Scaffolded with @skarab/skaffold

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文