从graphql-codegen

问题描述

我是apollo和graphql的新手。我尝试同时使用apollo-codegengraphql-codegen,并且希望在单个文件生成所有类型,如graphql-codegen中那样,但是在阿波罗中它会创建多个文件

使用graphql-codegen时遇到的问题是生成的类型不是我获取数据的格式。

使用apollo客户端use时查询我从后端获取的数据的格式为

data: {
  queryName : {... actualDataObject }

}

因此,阿波罗-codegen提供的示例查询输出为:-

export interface Login_logIn {
  __typename: "UserPayload";
  email: string;
  firstname: string;
  lastname: string;
}

export interface Login {
  logIn: Login_logIn;  // logIn is the queryname here
}

但是使用graphql-codegent输出的结果是:-

export type UserPayload = {
  __typename?: 'UserPayload';
  _id: Scalars['ID'];
  email: Scalars['String'];
  firstname: Scalars['String'];
  lastname: Scalars['String'];
};

是否有可能获得类似于阿波罗代码生成器的graphql代码生成器,即格式为:-

export type UserPayload {
  logIn : {                     //logIn is the queryname
    __typename?: 'UserPayload';
    _id: Scalars['ID'];
    email: Scalars['String'];
    firstname: Scalars['String'];
    lastname: Scalars['String'];
 }
}

以便在useQuery或useMutation挂钩中变得易于使用?通过使用graphql-codegen

 const [doLogin,{loading,error,data}] = useMutation<UserPayload,UserInputvariables>(
    LOGIN,{
      variables: {
        ...variables,}
    },);

解决方法

您需要将typescript-operations插件添加到codegen.yml

generates:
  types.ts:
    plugins:
      - typescript
      - typescript-operations

,并确保已将documents属性设置为指向查询所在的位置。

这将为每个操作生成两种其他类型-一种用于查询响应,另一种用于变量-然后可以将这两种类型都传递给您的钩子。

export type LoginMutationVariables = Exact<{ ... }>;


export type LoginMutation = (
  { __typename?: 'Mutation' }
  & { logIn: ... }
);

您可以查看有关插件here的其他详细信息。如果您使用的是Apollo,则可以考虑只使用generate the hooks for you的代码生成。