I have a server query:
const Query = {
returnFollowedUsers: async (root, args, {res, req}) => {
const following = await prisma.user.findUnique({
where: {id: req.userId || args.userId},
select: {
following: true,
},
});
const followedBy = await prisma.user.findUnique({
where: {id: args.userId},
select: {
followedBy: true,
},
});
return following.following;
}
}
A client query:
const ReturnFollowedUsers = gql`
query returnFollowedUsers($userId: Int) {
returnFollowedUsers(userId: $userId) {
id
email
user_name
}
}
`;
And a schema:
type Query {
returnFollowedUsers (userId: Int): [User]
}
At the moment I’m only returning the following
request. which works. But I would like to add the followedBy
request to that so I can retrieve all the data in 1 graphql request instead of doing a separate request for both.
So instead of returning return following.following;
in the server query I want to do something like return [following.following, followedBy.followedBy];
But I can’t figure out how to create the client query or schema for that request.
1 Like
Apparently you can define 2 servers queries:
const followedUsers = async (args, req) => {
const following = await prisma.user.findUnique({
where: {id: req.userId || args.userId},
select: {
following: true,
},
});
return following.following;
};
const followedBy = async (args, req) => {
const followedBy = await prisma.user.findUnique({
where: {id: req.userId},
select: {
followedBy: true,
},
});
return followedBy.followedBy;
};
const Query = {
returnFollowedUsers: async (root, args, {res, req}) => {
return await followedUsers(args, req);
},
returnFollowedBy: async (root, args, {res, req}) => {
return await followedBy(args, req);
},
}
And create a single client querie:
const ReturnFollowedUsers = gql`
query returnFollowedUsers($userId: Int) {
returnFollowedUsers(userId: $userId) {
id
email
user_name
}
returnFollowedBy(userId: $userId) {
id
email
user_name
}
}
`;
And a schema definition:
type Query {
returnFollowedUsers (userId: Int): [User]
returnFollowedBy (userId: Int): [User]
}
This returns a nested array which you can use:
data: {returnFollowedUsers: followedUsers = {}, returnFollowedBy: followedBy = {}}
1 Like
You mean something like this?
type User implements Node {
id: ID!
name: String
followers: UserConnection // or [User] if you don't use Relay-style pagination
following: UserConnection // or [User]
connections: UserConnection // returns both followers and following
}
query UserWithConnections($id: ID!, $prevEndCursor: String) {
user(id: $id) {
id
name
connections(first: 10, after: $prevEndCursor) {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
id
name
...
}
}
}
}
}