Skip to content

Add option for generate original type too #107

Closed
@anhdd-kuro

Description

@anhdd-kuro

I know this plugin produces mutation validators in the first place, but can we have an option for original type as well?
Nowadays we are not only uses zod for mutations, but also validates the data received from the server after fetching.
I know I can just add the ID to the schema using zod's extend, but it would be even more convenient if this plugin could do that.

type Member {
  id: ID!
  firstName: String
  lastName: String
}

type MemberInput {
  firstName: String
  lastName: String
}

// ->
// add this
export function MemberSchema(): z.ZodObject<Properties<Member>> {
  return z.object({
    id: z.string(),
    firstName: z.string().nullish(),
    lastName: z.string().nullish(),
  })
}

export function MemberInputSchema(): z.ZodObject<Properties<MemberInput>> {
  return z.object({
    firstName: z.string().nullish(),
    lastName: z.string().nullish(),
  })
}

so I can

import { graphQLClient, Member, MemberSchema } from "@/infra/graphql";

const getMembers = async (query = defaultQuery): Promise<Member[]> => {
  const { members } = await graphQLClient.request(query);

  const validatedData = MemberSchema().array().parse(members);
  // instead of 
  // const validatedData = MemberInputSchema().extend({ id: z.string() }).array().parse(members);

  return validatedData;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions