How to write GraphQL Query

2019-08-02 20:52发布

问题:

I have a working web graphql query as :

{
  me{
    ... on Student{

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

    }

  }
}

It returns the profile details of a particular student. I log using mutation and gets the token for a user.

I want to create a graphql file (ex. StudentProfile.graphql) in order to make fetch request (similar to http. get) using Apollo client.

I make this request to fetch the graphql query.

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
            }
        }

    }

How do I convert the following web query into a query in the .graphql file?

回答1:

so, you can call to create new document into Graphql server using a simple NSUrlSession

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()


回答2:

I'm not sure I completely understand your question, but you should be able to use HTTP to make queries. For most people, a *.gql file just contains the query as a String which they URLEncode. Below is an example of reading from a variable but you could do just the same reading the query from a file as a string/buffer.

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

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

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

If this does not answer your question, please help me better understand what you are asking, and I will try to revise my answer.