How to use gql with a Map inside User Defined Function

In the previous post, we have seen using gql function inside User Defined Function.

gql function accepts two parameters.

  • query: String - the GraphQL query to execute
  • values: Map - a map containing the set of variables used in query

In the previous post, we have seen use of gql without a map.
Let’s check how and when we should use the Map.

Example

We will rewrite addStudentData function again using gql function with a map.

type Mutation {
addStudentData(a: String, b: DateTime, c: String, d: String, e:Int, f: String,g: String, h:String):Json @tan(type:Groovy, inline: """
    return gql('''
    mutation addStudent($p: String, $q: DateTime, $r: String, $s: String, $t:Int, $u: String,$v: String, $w:String){
        upsert(
            values: { 
                StudentInformation: [
                    { 
                        name: $p,
                        dob: $q,
                        standard: $r,
                        division:$s,
                        contact: $t,
                        address : {
                            door:$u,
                            street:$v,
                            city: $w
                        }
                    }
                ] 
            }
        ) {
            id
        }
    }''', ['p':a , 'q': b, 'r': c , 's':d ,'t':e ,'u':f ,'v':g ,'w':h ])
  """)
}
  • Replace the \" " " with just ' ' ' . It removes string interpolation and variables are evaluated as GraphQL variables and not groovy variables.
  • Add GraphQL variables addStudent($p: String, $q: DateTime, $r: String, $s: String, $t:Int, $u: String,$v: String, $w:String) and map them with input parameters at the end. ['p':a , 'q': b, 'r': c , 's':d ,'t':e ,'u':f ,'v':g ,'w':h ]

Let’s execute the function!

mutation {
  addStudentData(a:"Abc \"XYZ\"", b: "2011-05-07", c:"VII", d: "A", e:897675786, f: "23", g: "3A Old Street",h:"New Delhi")
}
#result
{
  "data": {
    "addStudentData": {
      "data": {
        "upsert": [
          {
            "id": "01FS6E9BHC1C8TT5KSTAZ4BN0Y"
          }
        ]
      }
    }
  }
}

Check the input parameter a:"Abc \"XYZ\"". Here, we have used " in the input value. If we use gql without mapping variables as demonstrated in the previous post, it would result in the syntax error. With Map, we are using GraphQL variables instead of Groovy variables and the values get stored without String Interpolation.