Artemis 是一个 Swift 的 GraphQL 库,它允许你完全使用 Swift 与 GraphQL 后端交互 - 无需由字符串组成的不安全查询,也无需手动解析 Data
或 [String: Any]
响应。 Artemis 使用各种 Swift 功能来跟踪查询中使用的类型,因此以下请求:
// Artemis // Rendered GraphQL query
.query { query {
$0.country(arguments: .init(code: "CA")) { country(code: "CA") {
$0.name name
$0.continent { continent {
$0.name(alias: "continentName") continentName: name
} }
} }
} }
...是完全经过类型检查的 - 我们无法添加架构上不存在的字段,将字段放置在错误的位置,传递无效的参数,或者为我们的参数传递无效的类型。
执行该查询会生成一个 Partial<Country>
对象,你可以使用与普通 Country
实例相同的键路径和类型推断来与之交互。 Artemis 会用获取的数据填充响应对象 - 因此,此查询(及其响应)的处理方式如下:
let client = Client<Query>()
client.perform(.query { ... }) { result in
switch result {
case .success(let country):
country.name // "Canada"
country.continent?.name(alias: "continentName") // "North America"
country.languages // nil
case .failure(let error):
// error handling
}
}
Swift 中的 schema 表示形式也非常易读,并且与 GraphQL schema 语法保持相当接近的相似性。 上述查询的 schema 可能如下所示:
// Artemis // Original GraphQL schema
final class Query: Object { type Query {
@Field("country") country(code: String!): Country!
var country: (Country, CountryArgs.Type) }
struct CountryArgs: ArgumentsList { type Country {
var code: String name: String!
} languages: [String!]!
} continent: Continent!
}
final class Country: Object {
@Field("name") type Continent {
var name: String name: String!
}
@Field("languages")
var languages: [String]
@Field("continent")
var continent: Continent
}
final class Continent: Object {
@Field("name")
var name: String
}
不要让这个简单的例子低估了 Artemis - 它包含对 fragments、arguments、interfaces、inputs、aliases、mutations 和多个查询字段的完整支持。 它也非常轻量级(仅需要 Foundation
),因此支持 iOS、macOS 或 Swift 和 Foundation 可以运行的任何其他地方。
可以使用 Swift Package Manager 将 Artemis 添加到任何项目中。
将其添加到项目后,您可以查看Artemis 入门指南上的教程,以开始制作请求。
Aaron Bosnjak (电子邮件:aaron.bosnjak707@gmail.com, Twitter: @aaron_bosnjak)
Artemis 欢迎贡献者! 如果您有功能想法或错误修复,请随时打开一个 pull request。 问题和功能想法在此Trello board上进行跟踪。
Artemis 在 MIT 许可证下可用,因此您可以对其进行几乎任何您想做的事情。 与往常一样,请参阅 LICENSE 文件以获取更多信息。