graphql-tools
graphql-tools copied to clipboard
Add method to check if a given type/key already exists in MockStore
Is your feature request related to a problem? Please describe.
I've been thinking about the problem I asked about in https://github.com/ardatan/graphql-tools/discussions/3434 and trying to think of ways it could be solved relatively simply.
One of the core issues is that I can't tell whether or not a specific type in the union/interface is present in the store or not, since calling store.get(...) will always generate data for records not present in the store.
Describe the solution you'd like
If there were a method on MockStore to check if a given typename/key already exists in the MockStore then we could implement resolver logic to handle the union/interface cases.
For example:
resolvers: store => {
return {
Query: {
user: (_parent, { id }) => {
// If a Teacher record already exists in the store return it
if (store.has('Teacher', id)) {
return store.get('Teacher', id);
}
// If a Student record already exists in the store return it
if (store.has('Student', id) {
return store.get('Student', id);
}
// Otherwise fallback to the 'User' mock
return store.get("User", id);
}
}
}
}
Describe alternatives you've considered
I'm not sure of what alternatives might exist... perhaps there is some additional configuration that could be passed to MockStore to express this kind of relationship (interface/union with shared key uniqueness). But designing it seems tricky to get right given all the possible ways a relationship like this may be implemented in GraphQL.
Also, I imagine having a method to check if a record is present in the store could be useful for other purposes.
Additional context
After looking at the code for MockStore it seems that there is already a private property (store) for keeping track of data present in the MockStore, which seems like it could be used to implement this functionality on top of.
Thoughts?
We'd love to accept a PR for this change if anyone wants to work on it :)
Thanks! Glad to hear a PR for this would be considered. I have something implemented in a fork and I'll work on submitting a PR soon.