Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass GraphQLEnumType in mutation as a string value

I have following GraphQLEnumType

const PackagingUnitType = new GraphQLEnumType({
  name: 'PackagingUnit',
  description: '',
  values: {
    Carton: { value: 'Carton' },
    Stack: { value: 'Stack' },
  },
});

On a mutation query if i pass PackagingUnit value as Carton (without quotes) it works. But If i pass as string 'Carton' it throws following error

In field "packagingUnit": Expected type "PackagingUnit", found "Carton"

Is there a way to pass the enum as a string from client side?

EDIT: I have a form in my front end, where i collect the PackagingUnit type from user along with other fields. PackagingUnit type is represented as a string in front end (not the graphQL Enum type), Since i am not using Apollo Client or Relay, i had to construct the graphQL query string by myself. Right now i am collecting the form data as JSON and then do JSON.stringify() and then remove the double Quotes on properties to get the final graphQL compatible query.

eg. my form has two fields packagingUnitType (An GraphQLEnumType) and noOfUnits (An GraphQLFloat) my json structure is

{ 
  packagingUnitType: "Carton",
  noOfUnits: 10
}

convert this to string using JSON.stringify()

'{"packagingUnitType":"Carton","noOfUnits":10}'

And then remove the doubleQuotes on properties

{packagingUnitType:"Carton",noOfUnits:10}

Now this can be passed to the graphQL server like

newStackMutation(input: {packagingUnitType:"Carton", noOfUnits:10}) {
...
}

This works only if the enum value does not have any quotes. like below

newStackMutation(input: {packagingUnitType:Carton, noOfUnits:10}) {
...
}

Thanks

like image 515
krishnan Avatar asked Oct 29 '22 07:10

krishnan


1 Answers

GraphQL queries can accept variables. This will be easier for you, as you will not have to do some tricky string-concatenation.

I suppose you use GraphQLHttp - or similar. To send your variables along the query, send a JSON body with a query key and a variables key:

// JSON body
{
  "query": "query MyQuery { ... }",
  "variables": {
    "variable1": ...,
  }
}

The query syntax is:

query MyMutation($input: NewStackMutationInput) {
  newStackMutation(input: $input) {
    ...
  }
}

And then, you can pass your variable as:

{
  "input": {
    "packagingUnitType": "Carton",
    "noOfUnits": 10
  }
}

GraphQL will understand packagingUnitType is an Enum type and will do the conversion for you.

like image 95
yachaka Avatar answered Jan 02 '23 21:01

yachaka