nestjs-graphql-zod icon indicating copy to clipboard operation
nestjs-graphql-zod copied to clipboard

Can @QueryWithZod return array

Open railsstudent opened this issue 2 years ago • 9 comments

I have a query that wants to return user array. When I use @QueryWithZod([UserZod]), error occurs. I cannot find example that return array of object, please kindly advise.

export const UserZod = zod
  .object({
    id: zod.number().int(),
    name: zod.string(),
    username: zod.string(),
    email: zod.string().email(),
   )
  .required();

const ZodUserModel = modelFromZod(UserZod);

@ObjectType()
@Directive('@key(fields: "id")')
export class UserModel extends ZodUserModel {
  @Field(() => String, { complexity: 3 })
  name!: string;

  @Field(() => String, { complexity: 2 })
  email!: string;
}
  @Query(() => [UserModel])
  // @QueryWithZod(UserZod)
  async user(@Args('id', { type: () => Int }) id: number) {
    return this.usersService.getUser(id);
  }

railsstudent avatar Jun 16 '23 03:06 railsstudent

Hi @railsstudent.

Could you please try the following?

@QueryWithZod(UserZod.array())

So this simply creates a new zod scheme that will validate the array of User schemes. If this doesn't work, I may suggest other things or simply add this as a feature.

incetarik avatar Jun 16 '23 06:06 incetarik

@incetarik It does not work.

railsstudent avatar Jun 16 '23 10:06 railsstudent

Ok, I'll check this out, if it is possible to do in a nice way with what we already have, I'll give an example. Otherwise, I'll be adding a new feature for this.

incetarik avatar Jun 16 '23 12:06 incetarik

Thank you. I am happy that this library exists even though it is not the right time to use it in production codes.

railsstudent avatar Jun 19 '23 06:06 railsstudent

@railsstudent, maybe not right time to use for you or your project but yeah, I'll check that out now and see how I could do this

incetarik avatar Jun 19 '23 08:06 incetarik

I ran into the same problem. image

Darkhorse-Fraternity avatar Oct 27 '23 16:10 Darkhorse-Fraternity

Hi @Darkhorse-Fraternity ! Thank you for your response, I work on that issue but these days I'm pretty busy, when I complete this, I'l notify the ones I find here as soon as possible! For now, what you can do is simply validating your schema manually in the method body and throw an error/exception as you like. When I complete this, you will be notified.

incetarik avatar Oct 27 '23 22:10 incetarik