问题描述
我有以下GraphQLEnumType
I have following GraphQLEnumType
const PackagingUnitType = new GraphQLEnumType({
name: 'PackagingUnit',
description: '',
values: {
Carton: { value: 'Carton' },
Stack: { value: 'Stack' },
},
});
在变异查询中,如果我将PackagingUnit值传递为Carton(不带引号),则它起作用.但是,如果我以字符串"Carton"传递,则会引发以下错误
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?
我在前端有一个表单,在那里我从用户以及其他字段收集PackagingUnit类型.PackagingUnit类型在前端表示为字符串(不是graphQL Enum类型),由于我没有使用Apollo Client或Relay,因此我必须自己构造graphQL查询字符串.现在,我以JSON形式收集表单数据,然后执行JSON.stringify(),然后删除属性上的双引号以获取最终的graphQL兼容查询.
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.
例如我的表单有两个字段PackagingUnitType(一个GraphQLEnumType)和noOfUnits(一个GraphQLFloat)我的json结构是
eg. my form has two fields packagingUnitType (An GraphQLEnumType) and noOfUnits (An GraphQLFloat)my json structure is
{
packagingUnitType: "Carton",
noOfUnits: 10
}
使用JSON.stringify()将其转换为字符串
convert this to string using JSON.stringify()
'{"packagingUnitType":"Carton","noOfUnits":10}'
然后删除属性上的doubleQuotes
And then remove the doubleQuotes on properties
{packagingUnitType:"Carton",noOfUnits:10}
现在,它可以像这样传递给graphQL服务器
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}) {
...
}
谢谢
推荐答案
GraphQL查询可以接受变量.对于您来说,这将更加容易,因为您不必进行一些棘手的字符串连接.
GraphQL queries can accept variables. This will be easier for you, as you will not have to do some tricky string-concatenation.
我想您使用GraphQLHttp-或类似的东西.要沿着查询发送变量,请发送带有 query
键和 variables
键的JSON正文:
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": ...,
}
}
查询语法为:
query MyMutation($input: NewStackMutationInput) {
newStackMutation(input: $input) {
...
}
}
然后,您可以将变量传递为:
And then, you can pass your variable as:
{
"input": {
"packagingUnitType": "Carton",
"noOfUnits": 10
}
}
GraphQL将理解 packagingUnitType
是一种枚举类型,并将为您进行转换.
GraphQL will understand packagingUnitType
is an Enum type and will do the conversion for you.
这篇关于如何在突变中将GraphQLEnumType作为字符串值传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!