【问题标题】:GraphQL error: Expected type Int. Int cannot represent non-integer valueGraphQL 错误:预期类型为 Int。 Int 不能表示非整数值
【发布时间】:2023-03-17 17:31:01
【问题描述】:

我目前正在学习 GraphQLApollo 的 React,我有一个问题在网上找不到答案: 我已经完成了一个表单来为我的 mongoDB 发送数据,并且我有这个查询:

const addContactMutation = gql`
    mutation($name: String!, $address: String!, $vat: Int!, $zip: String!, $email: String!, $contact: Int!){
        addContact(name: $name, address: $address, vat: $vat, zip: $zip, email: $email, contact: $contact){
            name
            vat
            email
        }
    }
`

但是,我的 $vat$contact 是大数字,在提交表单时我收到此错误:

变量“$vat”得到无效值“232214336”;预期类型 Int。 int 不能表示非整数值

我应该使用哪种类型?

【问题讨论】:

    标签: reactjs error-handling graphql react-apollo apollo-client


    【解决方案1】:

    232214336没那么大,最大int数是9007199254740991

    console.log(Number.MAX_SAFE_INTEGER);

    我认为问题是您传递了一个字符串值"232214336",而错误提示为Expected type Int,因此您需要在将变量传递给突变之前或时将该值转换为整数使用parseInt()

    addContact({ variables: { vat: parseInt(vat, 10), contact: parseInt(contact, 10), ... } })
    

    【讨论】:

    • 如果 bigint 有那么大,你不能只用 parseInt 怎么办,那么对于真正的 bigint 值,你要为 graphQL 做什么?
    • @PositiveGuy 您可以使用自定义标量类型或 bigint-graphql js 库
    【解决方案2】:

    当类型为整数的数据库字段包含 NULL 值并且该字段由 GraphQL 查询返回时,也会发生此错误。解决此问题的一种方法是,将数据库设置为为整数字段提供默认值,以便在创建行时它们永远不会为 NULL。

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2021-10-29
      • 2017-12-12
      • 2019-05-18
      • 2010-09-24
      • 2021-12-12
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      相关资源
      最近更新 更多