【问题标题】:`parseValue` are not called for input parameter of a customised scalar type不为自定义标量类型的输入参数调用 `parseValue`
【发布时间】:2020-04-05 06:42:08
【问题描述】:

我这样定义一个模式:

const query = new GraphQLObjectType({
    name: 'Query',
    fields: {
      quote: {
        type: queryType,
        args: {
          id: { type: QueryID }
        },
      },
    },
  });
const schema = new GraphQLSchema({
    query,
  });

QueryID 是自定义的标量类型。

const QueryID = new GraphQLScalarType({
  name: 'QueryID',
  description: 'query id field',
  serialize(dt) {
    // value sent to the client
    return dt;
  },
  parseLiteral(ast) {
    if (ast.kind === 'IntValue') {
      return Number(ast.value);
    }
    return null;
  },
  parseValue(v) {
    // value from the client
    return v;
  },
});

客户端查询

query {
   quote(queryType: 1)
}

我发现当客户端向我的服务器发送查询时没有调用parseValue 方法。我可以看到parseLiteral 被正确调用。 在我能找到的大部分文档中,他们使用gql 来定义架构,他们需要将scalar QueryID 放在他们的架构定义中。但就我而言,我使用 GraphQLSchema 对象作为模式。这是根本原因吗?如果是,那么让它发挥作用的最佳方法是什么?我不想切换到gql 格式,因为我需要在运行时构建我的架构。

【问题讨论】:

    标签: node.js graphql apollo


    【解决方案1】:

    serialize 仅在响应中将标量发送回客户端时调用。它作为参数接收的值是解析器中返回的值(或者如果解析器返回了 Promise,则 Promise 解析为的值)。

    parseLiteral 仅在解析查询中的 literal 值时调用。文字值包括字符串 ("foo")、数字 (42)、布尔值 (true) 和 null。该方法作为参数接收的值是该文字值的 AST 表示。

    parseValue 仅在解析查询中的变量值时调用。在这种情况下,该方法从与查询一起提交的 variables 对象中接收相关 JSON 值作为参数。

    所以,假设这样的架构:

    type Query {
      someField(someArg: CustomScalar): String
      someOtherField: CustomScalar
    }
    

    序列化:

    query {
      someOtherField: CustomScalar
    }
    

    解析文字:

    query {
      someField(someArg: "something")
    }
    

    解析值:

    query ($myVariable: CustomScalar) {
      someField(someArg: $myVariable)
    }
    

    【讨论】:

    • 感谢您的回复。在我的例子中,我有一个参数定义为args: { id: { type: QueryID } },但parseValue 方法没有被触发。
    • 同样,这与您在服务器上定义参数的方式没有任何关系。这三种方法中只有一种会被调用。是否调用parseValueparseLiteral 取决于您是否使用变量。
    • 我确实在查询函数中使用了变量,例如:quote(queryType: 1)。变量值为1。但是方法parseValue没有被调用。
    • 是的,parseValue 用于变量,parseLiteral 用于文字值。 1 是文字值
    • 哦,我明白了。我误解了文字值和变量。谢谢老兄。
    猜你喜欢
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多