howtographql / graphql-js

https://www.howtographql.com/graphql-js/1-getting-started/
363 stars 124 forks source link

Improving the feed query #56

Open Drago96 opened 5 years ago

Drago96 commented 5 years ago

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.