【发布时间】:2020-11-03 16:48:14
【问题描述】:
如您所知,GraphQL 没有像 long int 这样的数据类型。所以,每当数字像10000000000 这样大的时候,它就会抛出这样的错误:Int cannot represent non 32-bit signed integer value: 1000000000000
为此,我知道两种解决方案:
- 使用标量。
import { GraphQLScalarType } from 'graphql';
import { makeExecutableSchema } from '@graphql-tools/schema';
const myCustomScalarType = new GraphQLScalarType({
name: 'MyCustomScalar',
description: 'Description of my custom scalar type',
serialize(value) {
let result;
return result;
},
parseValue(value) {
let result;
return result;
},
parseLiteral(ast) {
switch (ast.kind) {
}
}
});
const schemaString = `
scalar MyCustomScalar
type Foo {
aField: MyCustomScalar
}
type Query {
foo: Foo
}
`;
const resolverFunctions = {
MyCustomScalar: myCustomScalarType
};
const jsSchema = makeExecutableSchema({
typeDefs: schemaString,
resolvers: resolverFunctions,
});
这两种解决方案都将大整数转换为string,我宁愿不使用字符串(我更喜欢数字类型)。
【问题讨论】:
-
“将大整数转换为字符串”是什么意思?
-
意味着如果我使用这种方法,那么数据应该像
{ "a": "10000000000" }但它应该是。{"a" : 1000000000} -
数字过长的 JSON 很难解析,因此将它们放在字符串中更容易。鉴于任何超过 32 位的整数类型无论如何都将是自定义标量,这应该无关紧要。
-
那么,我的第一种方法是否适合实施?或者您还有其他选择吗?
-
好吧,您发布的代码 sn-p 实际上并没有做任何事情,但是是的,所有方法都将基于使用自定义标量类型。
标签: javascript node.js graphql bigint