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

pup*_*eno 9 apollo graphql apollo-server

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

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

我正在寻找类似于rake graphql:schema:dump使用GraphQL Ruby时的东西,您可以在服务器上运行它来生成schema.graphql.

Dan*_*den 14

您可以使用 Apollo CLI 来实现此目的。首先安装它:

npm install -g apollo
Run Code Online (Sandbox Code Playgroud)

然后运行此命令,如文档中所示:

apollo client:download-schema --endpoint=URL_OF_YOUR_ENDPOINT schema.graphql
Run Code Online (Sandbox Code Playgroud)

该命令将生成内省结果或 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))
Run Code Online (Sandbox Code Playgroud)

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