gpt4 book ai didi

swift - 如何编写 GraphQL 查询

转载 作者:搜寻专家 更新时间:2023-11-01 05:55:58 24 4
gpt4 key购买 nike

我有一个有效的 web graphql 查询:

{
me{
... on Student{

profile {
fullName
emailId
mobileNumber
civilId
address
city
state
country
zipCode
userProfilePic
userCategory
createdAt
updatedAt
}

}

}
}

它返回特定学生的个人资料详细信息。我使用 mutation 登录并获取用户的 token 。

我想创建一个 graphql 文件(例如 StudentProfile.graphql),以便使用 Apollo 客户端发出获取请求(类似于 http.get)。

我发出此请求以获取 graphql 查询。

func fetchStudentProfileDetails(){

let tokenString = "Bearer " + "....my token ..."

print(tokenString)


let newApollo: ApolloClient = {
let configuration = URLSessionConfiguration.default
// Add additional headers as needed
configuration.httpAdditionalHeaders = ["Authorization": tokenString]

let url = URL(string: "http://52.88.217.19/graphql")!

return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))
}()



newApollo.fetch(query: StudentProfileQuery()) { (result, error) in

self.profileDetailsTextView.text = "Success"


if let error = error {
NSLog("Error while fetching query: \(error.localizedDescription)");
self.profileDetailsTextView.text = error.localizedDescription
}
guard let result = result else {
NSLog("No query result");
self.profileDetailsTextView.text = "No query result"
return
}

if let errors = result.errors {
NSLog("Errors in query result: \(errors)")

self.profileDetailsTextView.text = String(describing: errors)

}

guard let data = result.data else {

NSLog("No query result data");

return
}
}

}

如何将以下网络查询转换为 .graphql 文件中的查询?

最佳答案

因此,您可以使用一个简单的 NSUrlSession 调用在 Graphql 服务器中创建新文档

let headers = ["content-type": "application/json"]
let parameters = ["query": "mutation { createProfile(fullName: \"test name\" emailId: \"test@email.com\") { id } }"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://<url graphql>")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})

dataTask.resume()

关于swift - 如何编写 GraphQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45167412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com