在 Apollo Kotlin 中的 GraphQL 文件类型
Apollo Kotlin 支持以下文件类型用于 GraphQL 定义:
.json用于 introspection schemas.graphqls用于 SDL schemas.graphql用于 operations (查询、mutations 和 subscriptions)
要了解更多关于 SDL schemas 的信息,请参阅关于 Apollo Kotlin 中 SDL支持的 博客文章。
Schemas
A GraphQL schema 描述了一个 graph 的数据类型以及这些类型之间的关系。 Apollo Kotlin 支持通过 introspection 获得的 JSON schemas,以及传统的 SDL schemas。
introspection schemas (.json)
您可以通过特殊的 introspection 查询 来获取 GraphQL 服务器 的架构。 introspection 查询 (假定服务器启用了 introspection )。像任何其他 GraphQL 服务器响应一样,返回的架构作为 JSON 格式提供,类似于以下内容:
{"data": {"__schema": {"queryType": {"name": "Query"},"mutationType": {"name": "Mutation"},"types": [...]}}}
一些 JSON 架构省略了顶级 data 字段。 Apollo Kotlin 支持这种省略。
像 Apollo Sandbox 这样的工具可以自动 introspect GraphQL 服务器并将其架构以 JSON(或 SDL)格式下载。 Apollo Kotlin 也可以使用 downloadApolloSchema Gradle 任务下载 introspection 架构:
./gradlew :app:downloadApolloSchema \--endpoint "https://example.com/graphql" \--schema schema.json
JSON introspection schemas are verbose and difficult to read or modify. For simplicity, you should consider JSON schemas read-only and convert them to SDL schemas if you need to make changes.
SDL schemas (.graphqls)
SDL (Schema Definition Language) is the canonical language for defining GraphQL schemas as defined in the GraphQL spec. It's much cleaner and more expressive than JSON for understanding a schema's structure. It also supports directives, unlike the JSON representation (see this issue):
type schema {query: Querymutation: Mutation}type Query {field: String @deprecated...}
您不能使用 introspection 从 GraphQL 终端直接下载 SDL 模式。但是,如果您在 --schema 选项中指定 .graphqls 扩展名,Apollo Kotlin 可以自动将 introspection 模式转换为 SDL:
./gradlew :app:downloadApolloSchema \--endpoint "https://example.com/graphql" \--schema schema.graphqls
Apollo Kotlin 也支持 .sdl 文件扩展名用于 SDL 模式,但使用 .sdl 的其他工具非常少。您应继续使用 .graphqls 扩展名。
操作(.graphql)
GraphQL 操作会针对图执行以检索或修改数据。
在 Apollo Kotlin 中,操作文件使用 .graphql (不带 's') 扩展名。这些文件仅包含 可执行定义 (查询、突变、订阅和/或片段):
query MyQuery {field1field2...}
Apollo Kotlin 将这些操作编译为类型安全的模型,您可以在运行时使用这些模型。