简体   繁体   中英

Graphql custom scalar, parseLiteral not called for null values?

I have a custom scalar

export const GraphQLObjectId = new GraphQLScalarType({
    name: "GraphQLObjectId",
    description: "whatever",

    ...

    parseValue(value) {
        console.log("parseValue");
        console.log(value);
        ...
    },

    parseLiteral(ast) {
        console.log("parseLiteral");
        console.log(ast);
        ...
    }
});

And a mutation like this

mutation {
  updateInstrument(
    input: {
      _id: "558ba89433d865236cb94bd5"
      name: "whatnot"
      issuerId: null
    }
  ) {
    _id
  }
}

where both _id and issuerId is of type GraphQLObjectId.

But only _id goes trough the parseLiteral function and not issuerId. If I change issuerId to "000000000000000000000000", it will also go trough parseLiteral(), but I intended to handle null in parseLiteral(), but it never ends up there.

What am I doing wrong?

This is expected behavior. null is conceptually a different kind of value in GraphQL than scalars or other types. All object fields and arguments normally accept null instead of an actual value -- that is, you may provide one or the other.

For example, the spec outlines these rules for coercing input object fields:

  • If the value null was provided for an input object field, and the field's type is not a non‐null type, an entry in the coerced unordered map is given the value null...
  • If a literal value is provided for an input object field, an entry in the coerced unordered map is given the result of coercing that value according to the input coercion rules for the type of that field.

In other words, the input is never coerced (parsed) if a null value is provided. The same applies to scalars:

For all types below, with the exception of Non‐Null, if the explicit value null is provided, then the result of input coercion is null.

The whole idea of a null value is tightly intertwined with GraphQL's rules for nullability. Null values are meant to be handled using the available types (namely, the Non-null type) -- trying to handle them inside a scalar's coercion logic is inadvisable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM