Apollo Server gql使用推荐
Apollo Server gql usage recommendation
我是第一次实现 GraphQL 服务器。在阅读文档时,我发现建议将 gql 与 typeDefs (https://www.apollographql.com/docs/apollo-server/migration-two-dot#existing-schema) 一起使用。我知道 gql 的用途,但我不明白如果构造函数在内部解析 typeDefs,为什么 Apollo Server 需要它。我的代码在有和没有它的情况下都有效。
为什么推荐使用gql?
更新 v1
由于将 gql 与 eslint 等工具结合使用,我立即注意到答案中描述的好处。没有 gql,可用的工具不够智能,无法区分模板字符串和 graphql。
这实际上只是 Apollo 团队的一个设计选择。 graphql-tools
,这是 apollo-server
在幕后使用的东西,支持 typeDefs
参数的多种类型,包括一个函数:
export type ITypeDefinitions = ITypedef | ITypedef[];
export type ITypedef = (() => ITypedef[]) | string | DocumentNode;
因为构造函数 ApolloServer
实际上只是将您的 typeDefs
传递给 graphql-tools
' makeExecutableSchema
,您可以将架构的类型定义作为字符串或一个功能,它仍然可以工作。至少在 JavaScript。 TypeScript 定义实际上明确指定 DocumentNode
作为类型,因此如果您使用的是 TypeScript,那将是不行的。
为什么 apollo-server
明确要求您传入一个 DocumentNode
(这就是 graphql-tag
returns)?正如 Apollo 开发者之一在 this PR 中指出的那样:
Supporting non-tagged-template-literals strings as typeDefs... makes it possible to define a document without a gql tag, which might be tempting, but it's worth reminding ourselves that there's some value to that tag since it makes it easier to do static analysis, automatic detection of string manipulation/variable interpolation (which is often an anti-pattern) and provides more ubiquitous editor syntax highlighting support.
如果您要传入 typeDefs
,您 应该 确保将它们作为 DocumentNode
,最简单的方法是使用 gql
标签。传递其中一种其他类型似乎可行,但文档和类型定义明确表示您不应该这样做。请记住,如果此类代码尚不存在,Apollo Server 总是会在未来的版本中引入逻辑,从而在传入错误类型时导致意外行为。
我是第一次实现 GraphQL 服务器。在阅读文档时,我发现建议将 gql 与 typeDefs (https://www.apollographql.com/docs/apollo-server/migration-two-dot#existing-schema) 一起使用。我知道 gql 的用途,但我不明白如果构造函数在内部解析 typeDefs,为什么 Apollo Server 需要它。我的代码在有和没有它的情况下都有效。
为什么推荐使用gql?
更新 v1
由于将 gql 与 eslint 等工具结合使用,我立即注意到答案中描述的好处。没有 gql,可用的工具不够智能,无法区分模板字符串和 graphql。
这实际上只是 Apollo 团队的一个设计选择。 graphql-tools
,这是 apollo-server
在幕后使用的东西,支持 typeDefs
参数的多种类型,包括一个函数:
export type ITypeDefinitions = ITypedef | ITypedef[];
export type ITypedef = (() => ITypedef[]) | string | DocumentNode;
因为构造函数 ApolloServer
实际上只是将您的 typeDefs
传递给 graphql-tools
' makeExecutableSchema
,您可以将架构的类型定义作为字符串或一个功能,它仍然可以工作。至少在 JavaScript。 TypeScript 定义实际上明确指定 DocumentNode
作为类型,因此如果您使用的是 TypeScript,那将是不行的。
为什么 apollo-server
明确要求您传入一个 DocumentNode
(这就是 graphql-tag
returns)?正如 Apollo 开发者之一在 this PR 中指出的那样:
Supporting non-tagged-template-literals strings as typeDefs... makes it possible to define a document without a gql tag, which might be tempting, but it's worth reminding ourselves that there's some value to that tag since it makes it easier to do static analysis, automatic detection of string manipulation/variable interpolation (which is often an anti-pattern) and provides more ubiquitous editor syntax highlighting support.
如果您要传入 typeDefs
,您 应该 确保将它们作为 DocumentNode
,最简单的方法是使用 gql
标签。传递其中一种其他类型似乎可行,但文档和类型定义明确表示您不应该这样做。请记住,如果此类代码尚不存在,Apollo Server 总是会在未来的版本中引入逻辑,从而在传入错误类型时导致意外行为。