Parsing GraphQL Mutation Arguments with Custom Scalars

Eve Porcello
InstructorEve Porcello
Share this video with your friends

Social Share Links

Send Tweet

If you want to be able to parse and serialize custom scalar types sent as arguments, you’ll add the parseValue and parseLiteral functions to the custom scalar constructor. In this video, we’ll take a closer look at these functions and how they can be used to transform data passed by the client.

Instructor: [00:00] First adjust the addDay mutation arguments to set date to the custom date scalar instead of a string. In the custom scalar resolver serialize is for outgoing data. parseValue and parseLiteral are for incoming data. When we receive the data as arguments, we can take that data and transform it before it's sent to the resolver.

[00:20] For now, let's just return value from parseValue, and we're going to return literal.value from the parseLiteral function, because the literal describes the whole AST, and our value is really found on that value key. If we run the mutation with the arguments sent as variables, parseValue is called. The value from the arguments object is passed to the parse value function and then returned.

[00:42] When we run the mutation with arguments sent inline as string, parseLiteral is called. We probably want to format this date to allow for users to type this in a variety of formats. Month/day/year, year/month/day, whatever. Let's take this value, convert it to a new date object, and then convert that to an ISO string.

[01:04] Same for the parse literal function. Now if we run this, the date value is transformed on the way in no matter what format it's passed in. Serialized will always be called when we query the date field. That's why we're getting a substring of this ISO date. If we remove the substring method, we'll see the whole thing.

[01:30] With a custom scalar, parseValue is invoked to parse client input passed as variables. parseLIteral is invoked to parse input passed inline in the query. Serialize is invoked when sending the value back to the client.