我创建了一个由Sequelize支持的Apollo服务器。
我也在用TypeScript编写应用程序。
这在Sequelize的主键(Int)概念与GraphQL的ID(特殊字符串)概念之间产生了冲突。
特别是,我有一个看起来像这样的GQL类型:
type Book {
id: ID!
Title: String!
}
和一个Typescript界面,大致如下所示:
export interface Book extends Model {
id: number;
name: string;
}
在我的解析器中,我具有以下内容:
book: async (parent, args, context) => {
const { models } = context;
const { id } = args;
const carrier = await models.Book.findByPk(id);
return carrier;
},
这将返回错误:
Types of property 'id' are incompatible.
Type 'number' is not assignable to type 'string'.
[这带给我我的问题
是否有一种方法可以强制ID解析为int而不是字符串?我想避免不得不重新映射Book
中的所有字段,只是要将ID转换为字符串
无法更改标量的行为-它被解析为字符串,因为这是规范指定的内容。您可以像这样将字符串转换为标量:
await models.Book.findByPk(parseInt(id, 10));
但是,您可以也仅使用Int
标量而不是ID
。这种方法的最大缺点是,如果不对架构进行重大更改,就无法切换到其他类型的ID(例如UUID)。使用Int而非ID将not影响由Apollo Client完成的缓存-只要该字段名为id
或_id
,无论其类型如何,它都将用于缓存键中。 >