I am using MongoDB as the database for my federated Apollo GraphQL API.
(My code is in TypeScript)
I have created a __resolveReference method for the Post resolvers object, and this works fine when I call it from the user service as follows:
User: {
...
firstPost(user: any) {
return { __typename: "Post", _id: user.firstPost };
},
}
...
}
However, when I call it on an array, it does not work. The following is how I call it:
User: {
...
posts(user: any) {
user.posts.map((x: any) => {
return { __typename: "Post", _id: x };
});
},
...
}
The post __resolveReference code follows:
Post: {
...
async __resolveReference(reference: any, { db }: any) {
console.log(reference);
console.log(reference._id);
try {
let r = (await db
.collection("posts")
.findOne({ _id: new ObjectID(reference._id) })) as Post;
console.log(r.content);
return r;
} catch (err) {
console.log(err.stack);
}
},
...
I know that the __resolveReference is not being "hit" when called from the posts resolver on the User object because the console.log()s are not shown in the Terminal, again, only from the posts resolver and not firstPost.
I would like some help in getting the __resolveReference working for arrays.
Thank you.
In Apollo Federation return array in
__resolveReferencedoesn't work properly if you want to return a array a solution is create a new type. For example, if you haveUserimplemented in one service and post in another a simple representation ofUserandPostModel are something like this:This method doesn't work. A solution is to create a new type in
Post Service:And in your
Userservice do this:And see if
__resolveReferencework withasync/awaitfunctions.