在 GraphQLScalarType 中 parseValue 和 parseLiteral 的区别是什么

通过查看关于自定义标量类型的 GraphQL 文档(我正在尝试创建自己的日期类型) ,我不确定 parseValueparseLiteral之间有什么区别。

Http://graphql.org/graphql-js/type/#graphqlscalartype

文档中似乎没有对函数的作用进行任何描述。

谁能告诉我要求是什么?我假设 serialize必须将标量序列化为字符串。是这样吗?我假设 parseLiteral 是将该字符串反序列化为?在我的例子中是 Date 类型。然而,在示例中-seralize 和 parseValue 是相同的函数-这表明它不是一个简单的反序列化方法。

12590 次浏览

The serialize method would be called when the value of the type is going to be sent to the client as a response. Since the values on the output is in the form of JSON, the return value of serialize could be anything. Could be string, number, array, object ...

The other two methods (parseValue and parseLiteral) are to read input.

In GraphQL there are two ways of reading input from client, one is inline in the query, like:

query {
allUsers(first:10) {
id
}
}

where 10 is the inline value for first argument. Since the input language for GraphQL is not exactly JSON, the value (here 10) is being parsed and converted to AST (Abstract Syntax Tree). In this case, parseLiteral comes to play. It inputs the AST and returns the parsed value of the type. Types could be as complex as JSON and parseLiteral could traverse the AST and return JSON.

The other way of reading input from clients is through variables:

query ($howMany: YourCustomType) {
users(first: $howMany) {
id
}
}

variables:

{
"howMany": {
"thisMany": 10
}
}

Since the variables are pure JSON, you don't need AST here, you already have JSON. That's where parseValue comes to play. It gets the input as JSON and returns whatever the query resolver should use.

function parseValue(value) {
let first = value.thisMany;
return first;
}

So, you could have different presentation when you read from variables than when you read values inline, but conceptually, they should be the same in terms of presentation. However since the "type" of input is different (inline is GraphQL and variable is JSON), the parsing algorithm could be different. That's why if you define it as input type, you need to provide two separate methods to read them.