使用 Apollo Server 时如何生成 schema.graphql 文件?

How do I generate the schema.graphql file when using Apollo Server?

使用Apollo Server编写GraphQL服务器时,如何在服务器上运行命令生成schema.graphql文件供客户端使用?注意:我没有使用 Apollo Client,我使用的是 Relay。

我知道我可以 运行 GraphQL 游乐场并从那里下载它,但我想要一个可以自动化的命令行。

我在使用 GraphQL Ruby 时正在搜索类似于 rake graphql:schema:dump 的内容,您可以在服务器上 运行 生成 schema.graphql.

您可以为此使用 Apollo CLI。首先安装它:

npm install -g apollo

然后运行这个命令如图docs:

apollo client:download-schema --endpoint=URL_OF_YOUR_ENDPOINT schema.graphql

该命令将根据用于输出文件的扩展名生成内省结果或 SDL 模式。

您的 ApolloServer 实例不会公开它创建的架构,但您也可以 运行 直接针对该实例进行内省查询:

const { getIntrospectionQuery, buildClientSchema, printSchema } = require('graphql')
const { ApolloServer } = require('apollo-server')

const apollo = new ApolloServer({ ... })
const { data } = await apollo.executeOperation({ query: getIntrospectionQuery() })
const schema = buildClientSchema(data)
console.log(printSchema(schema))

如果您将现有的 GraphQLSchema 实例传递给 Apollo Server,您也可以直接对其调用 printSchema