zod – 如何进行深度挑选

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

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:

  1. const UserSignUpResponse = UserModel.pick({
  2. username: true,
  3. // unable to perform the following action
  4. device: DeviceModel.pick({
  5. id: true,
  6. name: true,
  7. verified: false,
  8. })
  9. });

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:

  1. const UserSignUpResponse = UserModel.pick({
  2. username: true,
  3. // unable to perform the following action
  4. device: DeviceModel.pick({
  5. id: true,
  6. name: true,
  7. verified: false,
  8. })
  9. });

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

  1. 嵌套选择不被允许但你可以通过使用 `extend` 来绕过
  2. <!-- begin snippet: js hide: false console: true babel: false -->
  3. <!-- language: lang-js -->
  4. const UserSignUpResponse = UserModel.pick({
  5. username: true,
  6. }).extend({
  7. device: DeviceModel.pick({
  8. id: true,
  9. name: true,
  10. verified: false,
  11. })
  12. })
  13. <!-- 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 -->

  1. const UserSignUpResponse = UserModel.pick({
  2. username: true,
  3. }).extend({
  4. device: DeviceModel.pick({
  5. id: true,
  6. name: true,
  7. verified: false,
  8. })
  9. })

<!-- 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:

确定