graphql-js
graphql-js copied to clipboard
Improving the feed query
trafficstars
First of all, thanks for the great course. As someone with zero experience in GraphQL, the course helped me get a deeper understanding of how things work.
I feel like the feed query, defined here https://github.com/howtographql/graphql-js/blob/master/src/resolvers/Query.js#L1 , can be improved upon. Currently, the server makes a database request for both links and count, regardless of whether the client only asked for one or the other.
Modifying the code a bit, by rewriting the separate database calls into functions, seems to have fixed the issue.
const feed = (root, args, context, info) => {
const createWhereClause = () =>
args.filter
? {
OR: [
{ description_contains: args.filter },
{ url_contains: args.filter }
]
}
: {};
const links = () =>
context.prisma.links({
where: createWhereClause(),
skip: args.skip,
first: args.first,
orderBy: args.orderBy
});
const count = () =>
context.prisma
.linksConnection({
where: createWhereClause()
})
.aggregate()
.count();
return {
links,
count
};
};
module.exports = {
feed
};
I am not sure if this is the best approach to the problem, however this has reduced the redundant database calls.