I have a tree like structure in my backend described by the following GraphQL schema. Since dynamic recursion is not possible each node just contains the numerical id of it’s parent but not the object itself.
type Node {
id: Int!
parent_id: Int
}
type Query {
nodes(): [Node!]
}
On the Angular frontend I’m using Apollo Client to query all nodes. Now in the JS part it would be convenient to actually have recursive objects instead of just the parent_id
. Something like this:
interface Node {
id: number;
parent: Node|null;
}
I thought I could achieve the mapping from numerical parent_id
to parent
object by using Apollo’s type policies with a read
function on a local-only field:
cache: new InMemoryCache({
typePolicies: {
Node: {
fields: {
parent: {
read(_, {toReference, readField}) {
if (!readField("parentId")) {
return null;
}
return toReference({__typename: "Node", id: readField("parentId")})
},
},
Unfortunately the cache doesn’t seem to resolve the reference to the actual object as I was hoping but just returns an object representing the reference:
query GetNodes {
nodes {
id
parentId
parent @client
}
}
{"nodes":[{"__typename":"Node","parent":{"__ref":"Node:16"},"id":13,"parentId":16}]}
Am I overlooking something to make this work? Or can’t this be achieved transparently via the Apollo client’s cache?
Is there a more idiomatic way of how I could transmit the tree structure or transform the flattened one in the frontend back to a nested object representation? Or should I just keep the flattened one and lookup sub-object when needed?
4