当每次加载时 id
都不同时,我该如何(重新)查询对象? 我错过了什么?
const {nodeInterface, nodeField} = nodeDefinitions(
(globalId) => {
const {type, id} = fromGlobalId(globalId);
// This id is different every time (if page is reloaded/refreshed)
// How am I suppose to use this id for database query (e.g by id)?
// How do I get "the right ID"? (ID actually used in database)
console.log('id:', id);
// This is correct: "User"
console.log('type:', type);
if (type === 'User') {
// Function that is suppose to get the user but id is useless ..
return getUserById(id);
}
return null;
},
(obj) => {
if (obj instanceof User) {
return userType;
}
return null;
}
);
const userType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: globalIdField('User'), // Relay ID
_id: { type: GraphQLString }, // MongoDB ID
email: { type: GraphQLString },
name: { type: GraphQLString }
}),
interfaces: [nodeInterface]
});
最佳答案
全局 ID 主要用于重新获取 Relay 客户端存储中已有的对象。我将干燥并指向 an excellent related SO post ,这很好地解释了 Relay 中如何使用全局 ID。
如果您使用库中的辅助函数,例如 graphql-relay-js在 JavaScript 中,处理全局 ID 变得非常简单:
- 您确定服务器端对象类型 X 对应于 GraphQL 对象类型 Y。
- 向 X 添加一个字段
id
。此id
是本地 ID,对于 X 类型的任何对象都必须是唯一的。如果 X 对应于 MongoDB 文档类型,那么一个简单的方法是将_id
的字符串表示形式分配给此id
字段:instanceOfX.id = dbObject._id.toHexString()
. - 使用
globalIdField
辅助函数向 Y 添加字段id
。这个id
是全局ID,它在所有类型和对象中都是唯一的。如何生成这个全局唯一 ID 字段取决于实现。globalIdField
辅助函数根据对象 X 中的id
字段和类型名称X
生成此值。 - 在
nodeDefinitions
中,使用fromGlobalId
辅助函数从全局 ID 检索本地 ID 和类型。由于X中的id
字段是MongoDB中的_id
字段,因此您可以使用此本地ID来执行DB操作。首先从十六进制字符串转换为 MongoDB ID 类型。
您的实现中必须破坏本地 ID 分配(步骤 2)。否则,同一对象的 ID 在每次重新加载时都不会不同。
关于reactjs - 如何使用全局ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38834567/