0

我是阿波罗和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,
      }
    },
  );
4

1 回答 1

1

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

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

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

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

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


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

您可以在此处查看有关该插件的其他详细信息。如果您使用的是 Apollo,您可能会考虑让 codegen为您生成挂钩

于 2020-09-02T12:00:10.450 回答