【问题标题】:apollo client:codegen typescript with @client query fields阿波罗客户端:带有@client查询字段的codegen打字稿
【发布时间】:2019-05-19 06:25:28
【问题描述】:

对不起,如果这有点涉及,但我真的想关闭 能够在本地和本地使用 Apollo 客户端的最后一英里 服务器状态,随处可见自动 Typescript。也就是说,我有一个这样的查询:

query NavigationBarQuery($userId: Int, $portfolioCompanyId: Int!) {
  user(id: $userId) {
    id
    firstName
    lastName
    company {
      ... on CompanyInterface {
        companyType
      }
    }
  }
}

这是由我的 NavigationBar 组件导入的,如下所示:

import { NavigationBarQuery, NavigationBarQueryVariables } from '../../../graphql/generated/NavigationBarQuery';
import NAVIGATION_BAR_QUERY from '../../../graphql/NavigationBarQuery.graphql';

const NavigationBar = (vars: NavigationBarQueryVariables) => (
  <Query query={NAVIGATION_BAR_QUERY} variables={vars}>
    {({ loading, error, data, client }: QueryResult<INavigationBarClientQuery>) => {

     // etc.

使用本地模式文件(从 Graphene 转储)执行生成,如下所示:

apollo client:codegen --localSchemaFile ./build/schema.json --includes './src/graphql/**' --target typescript

这很好用,我得到了 TypeScript 类型和所有东西。

但是,我想包含一些本地状态,查询如下:

query NavigationBarQuery($userId: Int, $portfolioCompanyId: Int!) {
  user(id: $userId) {
    id
    firstName
    lastName
    company {
      ... on CompanyInterface {
        companyType
      }
    }
  }
  showNavbarUserInfo @client
}

如果我绕过 TypeScript,这个查询工作就好了,但是当我 尝试为其生成 Typescript 定义,生成 脚本发出此错误:

.../client/src/graphql/NavigationBarQuery.graphql: Cannot query field "showNavbarUserInfo" on type "Query".
{ ToolError: Validation of GraphQL query document failed
    at Object.validateQueryDocument (/Users/gavin/.config/yarn/global/node_modules/apollo-language-server/lib/errors/validation.js:32:19)
    at Object.generate [as default] (/Users/gavin/.config/yarn/global/node_modules/apollo/lib/generate.js:19:18)
    at write (/Users/gavin/.config/yarn/global/node_modules/apollo/lib/commands/client/codegen.js:64:54)
    at Task.task (/Users/gavin/.config/yarn/global/node_modules/apollo/lib/commands/client/codegen.js:83:46) name: 'ToolError' }

如果有的话,解决方法是什么?像往常一样,寻找例子。

【问题讨论】:

  • 加文,你有没有找到解决办法?
  • cnp 的回答如下

标签: typescript graphql apollo


【解决方案1】:

在此处提供更新的答案,因为@cnp 的答案缺少示例并且包含损坏的链接。

我的示例使用带有 npx 的新 Apollo CLI (https://github.com/apollographql/apollo-tooling),尽管它也可以在本地安装并在没有 npx 命令的情况下使用。

您需要通过添加新的 SDL 文件来使用仅限本地的字段来扩展您的架构。使用来自原始问题的示例查询,您将添加一个包含以下内容的文件(例如 schema.graphql):

extend type NavigationBar {
  showNavbarUserInfo: Boolean!
}

可选:如果您使用的是 VS Code 的 Apollo GraphQL 扩展,现在是时候让它知道在哪里可以找到新的 SDL 文件了,方法是将其正确添加到 includes apollo.config.js:

module.exports = {
  client: {
    includes: ['./schema.graphql'],
  },
};

现在在您的一个查询中包含 showNavbarUserInfo @client 本地字段,然后运行您的代码生成命令以包含您的原始 schema.json 文件和您的新 schema.graphql 文件:

npx apollo codegen:generate --localSchemaFile=schema.json,schema.graphql --target=typescript --includes=src/**/*.tsx --tagName=gql --addTypename --globalTypesFile=src/types/global-types.ts types

【讨论】:

    【解决方案2】:

    我刚刚解决了这个问题,所以希望这会对某人有所帮助。如果你的名字实际上是“某人”,而你恰好在寻找这些信息;这完全适合你!

    我的设置:

    我有两个架构文件。

    • 从我的 GraphQL 服务器中下拉的一个
    • 一个本地架构文件,其中包含用于在本地存储值的扩展属性

    依赖关系

    • @apollo/client": "^3.3.11"
    • @apollo/react-hooks": "^4.0.0"

    DevDependencies

    • @graphql-codegen/add": "^2.0.2"
    • @graphql-codegen/cli": "^1.20.1"
    • @graphql-codegen/typescript-apollo-client-helpers": "^1.1.2"
    • @graphql-codegen/typescript-operations": "^1.17.14"
    • @graphql-codegen/typescript-react-apollo": "^2.2.1"
    1. 为了更好地使用,我建议创建一个codegen.yml 文件(除非你已经看过很多黑客电影并且认为使用控制台进行所有这些选项更酷。或者,如果你只是想...... . 我不评判。)
    #./codegen.yml
    # See: https://graphql-code-generator.com/docs/getting-started/codegen-config
    overwrite: true
    schema:
      - "https://my-dev-server.com/v1/graphql":
          headers:
            'Authorization': 'Bearer [TOKEN]'
    generates:
      graphql/generated/generated.ts:
        # This is the defined client side schema file. It will first load the root schema defined above, and then load this (see: https://graphql-code-generator.com/docs/getting-started/schema-field#local-graphql-files)
        schema: graphql/client-schema.graphql
        # This is where the gql queries/subscripts/mutations reside
        documents: "graphql/queries/**/*.ts"
        plugins:
          - add:
              content: /* eslint-disable */
          - typescript
          - typescript-operations
          - typescript-react-apollo
        config:
          withHooks: true
    
    
    1. 设置本地架构文件。随心所欲地调用它,只要确保在codegen.yml 中正确设置值即可。我打电话给我的client-schema.graphql,因为我超级聪明....
    #./client-schema.graphql
    
    # see: https://www.apollographql.com/docs/react/local-state/managing-state-with-field-policies/
    directive @client on FIELD
    
    type LocalStateType {
      companyId: String
      contactId: String
    }
    
    extend type Users {
      localState: LocalStateType!
    }
    
    1. 完成上述操作后,根据您的 IDE,intellisense 应该开始接受更改。您需要在查询中使用@client 指令;像这样:
    export const QUERY_USER_BY_ID = gql`
      query getUserDetails($Id: uuid!) {
        Users_by_pk(Id: $Id) {
          EmailAddress
          Id
          localState @client {
            companyId
            contactId
          }
        }
      }
    `;
    
    1. 运行命令生成商品:
    • npx graphql-codegen --config codegen.yml

    关键说明

    • 我注意到,如果您为客户端 (client-schema.graphql) 文件设置了错误的路径,则不会显示错误。但是,如果您没有在输出中看到引用 @client 数据的生成数据,您就会知道自己错了。

    参考资料:

    【讨论】:

    • directive @client on FIELD 很不错,如果没有你的回答,我不会知道。
    【解决方案3】:

    为了使其工作,您需要使用您的客户端本地状态类型定义一个.graphql SDL 文件。然后,codegen 功能将看到此文件并将其与您的主模式合并。有关更多信息,请参阅https://github.com/apollographql/apollo-tooling/issues/949#issuecomment-459907307,以及此链接作为示例:https://github.com/apollographql/fullstack-tutorial/blob/master/final/client/src/resolvers.js#L4。注意extends Query 的使用。

    【讨论】:

    • 您能更新一下答案吗?链接不存在,所以如果我们能有新的例子,那就太好了。
    • @Mr.Ghamkhar 我在下面提供了更新的答案:stackoverflow.com/a/65458857/188740
    猜你喜欢
    • 2020-07-26
    • 2018-09-12
    • 2018-01-03
    • 2022-01-17
    • 2019-02-15
    • 2019-02-09
    • 1970-01-01
    • 2021-04-03
    • 2018-04-13
    相关资源
    最近更新 更多