GraphQL 是一种通过声明式数据查询语言来访问 API 的标准。它可以更好地处理多个数据源、复杂的查询、多个客户端的需求等情况。在编写 GraphQL Schema 时,将所有的类型和字段都写在一个文件中会导致文件过大、难以维护。本文将讲述如何在 GraphQL Schema 中使用模块化,提高代码复用性。
什么是 GraphQL Schema 模块化
在 GraphQL Schema 中,将 Schema 中的类型、查询、变量等功能,拆分到不同的文件中,这种拆分方式就是 GraphQL Schema 模块化。
为 GraphQL Schema 模块化提供支持的工具
有几个工具可以帮助我们在 GraphQL Schema 中实现模块化:
graphql-import
:支持将 GraphQL schema、query、mutation、subscription、类型定义等模块引入到其他模块中。它可以导入.graphql
文件、.gql
文件、JS
文件、TS
文件、.json
文件等。graphql-tools
:它是一个基于 GraphQL 的工具集,通过它可以方便地将.graphql
文件转换为 JavaScript 中的类型定义,以及将Resolver
和Schema
中的功能模块化。
如何使用 GraphQL Schema 模块化
使用 graphql-import
导入模块
- 安装
graphql-import
npm install graphql-import
- 创建一个
Query
类型的文件Query.graphql
,定义一个查询类型:
# Query.graphql type Query { user(id: ID!): User }
- 创建
User.graphql
文件,定义用户类型:
# User.graphql type User { id: ID! name: String! age: Int! }
- 在
Query.graphql
中导入User.graphql
:
# Query.graphql #import "./User.graphql" type Query { user(id: ID!): User }
- 使用
fs
模块读取Query.graphql
文件后直接将其转换为 Schema。
-- -------------------- ---- ------- -- ---------- ----- - -------------------- - - ------------------------ ----- - ------------ - - ------------------------- ----- -- - ------------- ----- -------- - ------------------------------- ----- --------- - -- -------------- - ---------------------- --------- ---------- --
- 这时我们可以使用 GraphQL Playground 等工具访问用户类型和 query 类型:
使用 graphql-tools
模块化
graphql-tools
的模块化方式与 graphql-import
相似,不同的是使用方式。
- 安装
graphql-tools
npm install graphql-tools
- 创建
user.js
文件
// user.js module.exports = ` type User { id: ID! name: String! age: Int! } `
- 创建
userQuery.js
文件
// userQuery.js module.exports = ` user(id: ID!): User `
- 在
index.js
中将 userQuery 和 user 组合在一起:
-- -------------------- ---- ------- -- -------- ----- - -------------------- - - ------------------------ ----- ---- - ----------------- ----- --------- - ---------------------- ----- -------- - - ---- ----- - ------------ - ------- - ----- --------- - -- -------------- - ---------------------- --------- --------- --
- 启动 GraphQL 服务,即可使用 Schema:
以上是使用 graphql-tools
和 graphql-import
进行 GraphQL Schema 模块化的步骤及代码,使用这些工具可以很好地提高 Schema 的复用性以及维护性。
总结
模块化可以是代码更加清晰易懂,节约时间和精力,提高代码质量,每个模块是可以拆分和重组的, 模块化的结构简单易懂,另外,schema的增删该也更加方便。GraphQL Schema 模块化的方法有很多,以上只是其中几种,读者可以根据自己实际项目需求选择合适的方法来提高 GraphQL Schema 的维护性和复用性。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/64f51751f6b2d6eab3dcf03d