Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Parsing GraphQL Mutation Arguments with Custom Scalars

    Eve PorcelloEve Porcello

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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.

    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.