igortp
igortp

Reputation: 179

Passing variables to query with complex input types

According to graphQl docs:

When you're passing arguments in code, it's generally better to avoid constructing the whole query string yourself. Instead, you can use $ syntax to define variables in your query, and pass the variables as a separate map.

https://graphql.org/graphql-js/passing-arguments/

In this context, I'm trying to query the following schema:

const typeDefs = "
input OrderInputData {    
  date: String!
  time: String!
  frequency: String!
  extras: [Int!]
  mailAlarm: String
  phoneAlarm: String
  rating: Float
  comments: String
}

type Mutation {
  updateIntent(
    paymentIntentId: String, 
    setupIntentId: String, 
    pairIntentId: String,
    orderInput: OrderInputData): Boolean
}"

I'm having a bit of difficulty to build the query respecting graphQl's better practices, since this case is more complex than the one depicted on the documentation, due to the presence of a nested document(OrderInputData). This is what I have up to know:

  const dummyData = {
    date: "11/11/2020",
    frequency: "One time",
    time: "6:17 PM",
    mailAlarm: "teste",
    phoneAlarm: "teste",
    extras: [1, 3, 7],
  };

const graphqlQuery = {
      query: `
      mutation updateIntent (
        $paymentIntentId: String, 
        $pairIntentId: String, 
        $orderInput: { 
          date: String!, 
          time: String!, 
          frequency: String!, 
          extras: [Int!], 
          mailAlarm: String, 
          phoneAlarm: String
        }) {
      updateIntent (
        paymentIntentId: $paymentIntentId, 
        pairIntentId: $pairIntentId, 
        orderInput: { 
          date: $date, 
          time: $time, 
          frequency: $frequency, 
          extras: $extras, 
          mailAlarm: $mailAlarm, 
          phoneAlarm: $phoneAlarm
        })
      }`,
      variables: {
        paymentIntentId: paymentIntentId, 
        pairIntentId: setupIntentId,
        "orderInput.date": dummyData.date, 
        "orderInput.time": dummyData.time, 
        "orderInput.frequency": dummyData.frequency, 
        "orderInput.extras": dummyData.extras, 
        "orderInput.mailAlarm": dummyData.mailAlarm, 
        "orderInput.phoneAlarm": dummyData.phoneAlarm
      }

What is my mistake?

Upvotes: 0

Views: 2094

Answers (1)

xadm
xadm

Reputation: 8418

Generally, prepare [and pass as variable] object for any complex input type defined in [API, BE] mutation specs.

variables: {
    paymentIntentId: paymentIntentId, 
    pairIntentId: setupIntentId,
    orderInput: { date: orderInput.date,
    ...

... or in this case (orderInput defined earlier) simply

orderInput: orderInput

... or of course (if name matches) just:

variables: {
    paymentIntentId: paymentIntentId, 
    pairIntentId: setupIntentId,
    orderInput,
    ...

In query/mutation simply:

$orderInput: OrderInputData

followed by

orderInput: $orderInput` 

Upvotes: 1

Related Questions