GraphQL大整数错误:Int不能表示非32位有符号整数值

Men*_*des 9 javascript mongoose mongodb graphql

我试图在MongoDB使用中存储UNIX时间戳GraphQL,但它认为GraphQL有一个限制来处理整数.看下面的变异:

const addUser = {
    type: UserType,
    description: 'Add an user',
    args: {
        data: {
            name: 'data',
            type: new GraphQLNonNull(CompanyInputType)
        }
    },
    resolve(root, params) {

        params.data.creationTimestamp = Date.now();

        const model = new UserModel(params.data);
        const saved = model.save();

        if (!saved)
            throw new Error('Error adding user');

        return saved;
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

  "errors": [
    {
      "message": "Int cannot represent non 32-bit signed integer value: 1499484833027",
      "locations": [
        {
          "line": 14,
          "column": 5
        }
      ],
      "path": [
        "addUser",
        "creationTimestamp"
      ]
    }
Run Code Online (Sandbox Code Playgroud)

我目前GraphQLInteger在类型定义上使用此字段:

creationTimestamp: { 
    type: GraphQLInt
}
Run Code Online (Sandbox Code Playgroud)

如果没有更大的GraphQLInt可用空间,我该如何解决这种情况GraphQL

Dan*_*den 10

你可能最好使用像GraphQL Date这样的自定义标量.还有一个"龙"型可用在这里.或者你可以推出自己的自定义类型; 有一个从阿波罗一个很好的例子在这里.

如果你很好奇为什么GraphQL不支持更大的东西,你可以在Github上查看这个问题.


joh*_*pin 8

\xe2\x9a\xa0\xef\xb8\x8f 不推荐,因为可能会损失精度...

\n

...但是如果您想要快速修复(也许您没有时间实现自定义标量),您可以使用类型Float而不是Int.

\n

  • 我的意思是我知道,但是当我遇到这个错误时,我根本没有时间重构我的所有模式,就像有效答案中提到的那样:/这个错误有点意外,因为简单的时间戳不适合(并且请你自己尝试一下,因为这个“技巧”有效,我在[这个问题](https://github.com/graphql/graphql-js/issues/1003))中找到了它。所以,是的,也许这不是最好的答案,但它绝对可以帮助面临同样问题的人,所以没有理由否决它。 (2认同)