GraphQL 是一种用于 API 的查询语言,它可以让客户端按需请求需要的数据。为了方便使用 GraphQL,我们可以使用 npm 包 graphql-config
来管理 GraphQL 相关配置。
安装
可以通过以下命令来安装 graphql-config
:
npm install graphql-config
配置文件
在项目根目录下创建一个 .graphqlrc.yml
文件,并添加如下内容:
schema: ./path/to/schema.graphql documents: ./src/**/*.graphql extensions: endpoints: default: http://localhost:4000/graphql
schema
:指定 GraphQL schema 文件路径。documents
:指定包含 GraphQL 查询文档的文件夹路径。extensions.endpoints.default
:指定 GraphQL API 的 URL。
使用
命令行工具
graphql-config
提供了命令行工具,可以用来检查配置文件是否正确,显示可用的配置信息等。例如,可以使用以下命令来列出所有的 GraphQL endpoint:
npx graphql list-endpoints
编程接口
graphql-config
还提供了编程接口,可以在 JavaScript 中直接读取配置信息。例如,可以使用以下代码来获取默认 endpoint 的 URL:
const { getGraphQLConfig } = require('graphql-config'); const config = getGraphQLConfig(); const endpoint = config.getDefault().endpoint; console.log(`Endpoint URL: ${endpoint}`);
示例
以下是一个使用 graphql-config
的示例:
# ./src/user.graphql query GetUser($id: ID!) { user(id: $id) { id name email } }
-- -------------------- ---- ------- -- -------------- ----- - ----- - - ----------------------- ----- - ------------- - - --------------------------- ----- - ---------------- - - -------------------------- ----- -------- ------ - ----- ------ - ------------------- ----- -------- - ----------------------------- ----- ------ - --- ----------------------- - ----- --- ----- ----- - - ----- ------------ ---- - -------- ---- - -- ---- ----- - - -- ----- --------- - - --- --- -- ----- ---- - ----- --------------------- ----------- ------------------ - ----------------------------展开代码
在上面的示例中,我们使用 graphql-config
来管理 GraphQL 相关配置,然后使用 graphql-request
包来发起 GraphQL 查询,并使用 cross-fetch
包来发送 HTTP 请求。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/42601