我遇到了apollo-codegen无法成功生成打字稿代码的情况。

对于graphql文件(generated/schema.graphql):

type Author {
  id: Int!
  firstName: String
  lastName: String
  posts: [Post]
}

type Post {
  id: Int!
  title: String
  author: Author
  votes: Int
}


然后我运行:

$apollo-codegen introspect-schema generated/schema.graphql --output generated/schema.json

这会生成一个./generated/schema.json,其中似乎包含相关信息(我看到有关Author及其属性以及Post及其属性的信息)。

然后我跑

$apollo-codegen generate generated/schema.graphql --schema generated/schema.json --target typescript并获得(有效)空输出。

//  This file was automatically generated and should not be edited.
/* tslint:disable */
/* tslint:enable */


我也尝试过生成.swift文件,具有类似的空输出。

Apollo代码生成版本为:

"apollo-codegen": "^0.11.2",


有人看到我在做什么错吗?

最佳答案

我是apollo-codegen上的合作者。很高兴听到您正在尝试!

您看不到任何输出,因为apollo-codegen会基于项目中的GraphQL操作(查询,变异)生成类型,而不仅仅是基于架构中的类型。

根据我们的经验,很少发送完整的GraphQL类型的查询。相反,我们发现基于graphql操作的类型最有用。

例如,给定您提供的类型,您可以编写查询:

query AuthorQuery {
  authors {
    firstName,
    lastName
  }
}


将会生成的类型(并且您可能希望在使用此查询结果的代码中使用该类型)

type AuthorQuery = {
  authors: Array<{
    firstName: string,
    lastName: string
  }>
}


请注意,您将如何在React组件(或类似组件)中使用AuthorQuery类型,而不会使用Author类型,因为它会包含比实际请求更多的字段。

但是,如果您确实有一个从graphql模式到打字稿的1:1类型用例,请在项目本身上提出问题,我很乐意在此进行讨论:)

10-07 19:09
查看更多