zod – 如何进行深度挑选

huangapple go评论72阅读模式
英文:

zod - How to deepPick

问题

I am using zod with fastify. I have a UserModel that consists of the username and device properties. The username field is a string, while the device field is an object (DeviceModel) with "name", "id", and "verified" fields.

During the sign-up process, I want to return the complete user object, but without including certain properties nested inside the DeviceModel. To achieve this, I aim to create a UserSignUpResponse. However, I do not want the entire DeviceModel to be included in the response. I have devised the following solution:

const UserSignUpResponse = UserModel.pick({
  username: true,
  // unable to perform the following action
  device: DeviceModel.pick({
    id: true,
    name: true,
    verified: false,
  })
});

My question is whether I should ".pick fields from the UserModel schema and extend it with a device field with the same properties as the DeviceModel?

英文:

I am using zod with fastify. I have a UserModel that consists of the username and device properties. The username field is a string, while the device field is an object (DeviceModel) with "name", "id" and "verified" fields.

During the sign-up process, I want to return the complete user object, but without including certain properties nested inside the DeviceModel. To achieve this, I aim to create a UserSignUpResponse. However, I do not want the entire DeviceModel to be included in the response. I have devised the following solution:

const UserSignUpResponse = UserModel.pick({
  username: true,
  // unable to perform the following action
  device: DeviceModel.pick({
    id: true,
    name: true,
    verified: false,
  })
});

My question is whether I should ".pick fields from the UserModel schema and extend it with a device field with the same properties as the DeviceModel ?

答案1

得分: 1

嵌套选择不被允许但你可以通过使用 `extend` 来绕过

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    const UserSignUpResponse = UserModel.pick({
      username: true,
    }).extend({
      device: DeviceModel.pick({
        id: true,
        name: true,
        verified: false,
      })
    })

<!-- end snippet -->
英文:

Nested pick is not allowed, but you can bypass that with the use of extend:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const UserSignUpResponse = UserModel.pick({
  username: true,
}).extend({
  device: DeviceModel.pick({
    id: true,
    name: true,
    verified: false,
  })
})

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月27日 17:25:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563437.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定