GraphQLer 是一个 Swift 库,用于生成 GraphQL 文档(即你可以发送到服务器的内容)。它遵循 2018 年 6 月规范。 它不执行网络连接、数据绑定或解析。
它是一个纯 Swift 库,除了标准库之外没有任何依赖项,因此它应该可以在任何可以使用 Swift 的环境中使用。
GraphQLer 实现了从 GraphQL 规范中的类型到 Swift 类型的直接映射。 这些类型与你在规范中找到的类型相同:Document、ExecutableDefinition、Operation、Field、Selection、SelectionSet 等。 这意味着如果你知道格式,它应该很容易,但它可能很冗长。 你可能需要在它之上添加一些层,以方便使用你需要的 API。
使用 GraphQLer 类型和便捷方法,你可以编写如下代码
import GraphQLer
let gql = Document(definitions: [
.query([
.field(named: "repository", arguments: ["owner": "juri", "name": "graphqler"], selections: [
.inlineFragment(on: "Repository", selections: [
.field(named: "defaultBranchRef", selections: [
.field(named: "target", selections: [
.inlineFragment(on: "Commit", selections: [
.field(named: "history", arguments: ["first": 10], selections: [
.field(named: "edges", selections: [
.field(named: "node", selections: [
.inlineFragment(on: "Commit", selections: [
"committedDate",
"message"
])
])
])
])
])
])
])
])
])
])
])
let str = try gql.compactString()
如果你正在构建许多不同的 GraphQL 文档,最好为你在意的事情添加一些辅助函数。 如果你使用扩展来完成,你可以在 Xcode 中获得自动完成支持
import GraphQLer
/* extensions */
let gql = Document(definitions: [
.query([
.repository(owner: "juri", name: "graphqler", selections: [
.inlineFragment(.onRepository([
.defaultBranchRef([
.target([
.inlineFragment(.onCommit([
.history(first: 10, selections: [
.edges([
.node([
.inlineFragment(.onCommit([
.committedDate,
.message,
]))
])
])
])
]))
])
])
]))
])
])
])
let str = try gql.compactString()
你可以尝试在包含的 Xcode 游乐场中自己运行这些示例。 如果你在 Xcode 中打开 Package.swift
,你应该也能看到游乐场。