如何编写GraphQL查询

时间:2017-07-18 12:53:57

标签: swift facebook-graph-api authorization token graphql

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

{
  me{
    ... on Student{

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

    }

  }
}

它返回特定学生的个人资料详细信息。我使用变异记录并获取用户的令牌。

我想创建一个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
            }
        }

    }

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

2 个答案:

答案 0 :(得分:6)

所以,您可以使用简单的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()

答案 1 :(得分:0)

我不确定我是否完全理解您的问题,但您应该能够使用HTTP进行查询。对于大多数人来说,*.gql文件只包含查询作为他们URLEncode的字符串。下面是从变量读取的示例,但您可以将文件中的查询作为字符串/缓冲区读取相同的内容。

const myQuery = `{
  user {
    name
  }
}`;

const queryURL = "http://52.88.217.19/graphql/?query=" + URLEncode(myQuery);

fetch(queryURL)
  .then((result) => {
    console.log(result);
  })

如果这不能解答您的问题,请帮助我更好地理解您的要求,我会尝试修改我的答案。