Queries, Mutations & Subscriptions#
SwiftGraphQL lets you query data, perform mutations and even listen for subscriptions. Since queries and mutations don't differ much on the API level, they share the same method send
. Subscriptions, on the other hand, use listen
method. Each of these functions has a type check that makes sure you can actually query what you are querying and mutating what is mutable.
When it comes to the usage flow, all three operations follow the same principle.
- You create a query selection that tells the client what it should query and how it should decode the result.
- Using
send
orlisten
you communicate with the server.
Examples#
let query = Selection.Query {
let list = try $0.humans(human.list)
let nullable = try $0.human(id: "100", human.nullable)
return list
}
send(query, to: "http://localhost:4000") { result in
if let data = try? result.get() {
print(data)
}
}
let subscription = Selection.Subscription {
let list = try $0.humans(human.list)
let nullable = try $0.human(id: "100", human.nullable)
return list
}
// Start the event.
let task = listen(for: subscription, on: "ws://localhost:4000/graphql") { result in
if let data = try? result.get() {
print(data)
}
}
// To close the socket.
task.close()
❗️ NOTE: You should handle the closing of sockets. SwiftGraphQL intentionally doesn't handle websocket state and only implements the decoding and sending mechanism.