【问题标题】:Getting types generated similar to apollo codegen from graphql-codegen从 graphql-codegen 获取类似于 apollo codegen 生成的类型
【发布时间】:2020-12-21 07:00:20
【问题描述】:

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

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

当使用 apollo 客户端 useQuery 时,我从后端获取的数据格式为

data: {
  queryName : {... actualDataObject }

}

所以 apollo -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'];
};

是否可以像 apollo codegen 一样输出 graphql-codegen,即格式为:-

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

让它在 useQuery 或 useMutation hook 中变得容易使用?通过使用 graphql-codegen

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

【问题讨论】:

    标签: graphql apollo apollo-client graphql-codegen


    【解决方案1】:

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

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

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

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

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

    您可以查看有关插件here 的更多详细信息。如果您使用的是 Apollo,您可能会考虑使用 codegen 只是 generate the hooks for you。

    【讨论】:

    • 我没有使用 codegen 创建钩子,所以没有将文档属性添加到 codegen.yml。您的回答解决了问题并创建了我需要的类型.. 谢谢。
    猜你喜欢
    • 2019-07-30
    • 2020-03-22
    • 2019-11-12
    • 2021-07-08
    • 2021-12-29
    • 2019-11-16
    • 2020-02-29
    • 2019-07-19
    • 2021-09-02
    相关资源
    最近更新 更多