背景:我们的产品老式后端完全用Java编写。我们正在尝试为其实现GraphQL功能,以便新的基于React的前端可以在需要时从那里获取信息。
以下GraphQL查询返回有关实物投资组合的信息,并且在GraphiQL实例中运行良好。
query Fund($portfolioId: Long) {
fund: portfolio(id: $portfolioId) {
id
fundName: name
}
}
问题:该查询在React中不起作用(使用Apollo Client)。问题似乎在于期望Long
类型,而不是number
或string
。
是否有一种方法可以解决此问题,而无需更改后端的架构?
Long不是GraphQL参考规范的内置标量类型。您必须编写自己的自定义标量解析器。这是一个实现https://github.com/chadlieberman/graphql-type-long/
var GraphQLLong, GraphQLScalarType, Kind, MAX_LONG, MIN_LONG, coerceLong, parseLiteral;
GraphQLScalarType = require('graphql').GraphQLScalarType;
Kind = require('graphql/language').Kind;
MAX_LONG = Number.MAX_SAFE_INTEGER;
MIN_LONG = Number.MIN_SAFE_INTEGER;
coerceLong = function(value) {
var num;
if (value === '') {
throw new TypeError('Long cannot represent non 52-bit signed integer value: (empty string)');
}
num = Number(value);
if (num === num && num <= MAX_LONG && num >= MIN_LONG) {
if (num < 0) {
return Math.ceil(num);
} else {
return Math.floor(num);
}
}
throw new TypeError('Long cannot represent non 52-bit signed integer value: ' + String(value));
};
parseLiteral = function(ast) {
var num;
if (ast.kind === Kind.INT) {
num = parseInt(ast.value, 10);
if (num <= MAX_LONG && num >= MIN_LONG) {
return num;
}
return null;
}
};
GraphQLLong = new GraphQLScalarType({
name: 'Long',
description: 'The `Long` scalar type represents 52-bit integers',
serialize: coerceLong,
parseValue: coerceLong,
parseLiteral: parseLiteral
});
module.exports = GraphQLLong;