Reputation: 6967
How am I supposed to (re)query the object when id
is different on every load? What am I missing?
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]
});
Upvotes: 2
Views: 3498
Reputation: 3399
Global ID is primarily used for refetching objects which are already in the Relay client store. I'll DRY and point to an excellent related SO post, which nicely explains how global ID is used in Relay.
If you use helper functions from libraries, for example, graphql-relay-js in JavaScript, dealing with global ID becomes pretty straight-forward:
id
to X. This id
is the local ID and it must be unique for any object of type X. If X corresonds to a MongoDB document type, then a simple approach is to assign the string representation of _id
to this id
field: instanceOfX.id = dbObject._id.toHexString()
.id
to Y by using globalIdField
helper function. This id
is the global ID and it's unique across all types and objects. How this globally unique ID field is generated depends on the implementation. The globalIdField
helper function generates this from the id
field in object X and the type name X
.nodeDefinitions
, retrieve local ID and type from global ID by using fromGlobalId
helper function. Since, the id
field in X was the _id
field in MongoDB, you can use this local ID to perform DB operations. Convert from hex string to MongoDB ID type first.Local ID assignment (step 2) must be broken in your implementation. Otherwise, ID of the same object would not be different on every reload.
Upvotes: 2