Skip to content

A utility for eager-loading related resources based on the structure of a GraphQL Query

License

Notifications You must be signed in to change notification settings

jsamchineme/graphql-sequelize-query-loader

Repository files navigation

graphql-sequelize-query-loader

Convert GraphQL Query to query options for Sequelize models facilitating eagerloading of associated resources.

codecov Build Status codebeat badge License

Overview

Essentially, the tool expects that all sequelize models have set on them the appropriate associations to all related resources. Then, when given a GraphQL query, it parses the info object made available as a parameter in GraphQL Query Resolvers, producing an object which includes ONLY the selected resources and with ONLY the specified attributes.
This solves for the N + 1 problem with database querying, as well as the issue of over-fetching of table attributes in result sets.

Installation

$ npm install --save graphql-sequelize-query-loader

Pre-requisites

In order to use the helper to eagerload related entities, you need to have setup the associations on the Sequelize Models.

Features

  • maps the selected fields (in all models found in a GraphQL query) to the attributes option for Sequelize `Model.Find
  • maps included models found in the GraphQL query to include option properties
  • converts scope argument in GraphQL query and turns them to where option properties

Usage

import queryLoader from 'graphql-sequelize-query-loader';
import models from 'path/to/sequelize/models';

/**
 * dictionary of what sequelize models respectively match the named resources
 * captured on the graphql schema
 */
const includeModels = {
  articles: models.Article,
  article: models.Article,
  owner: models.User,
  category: models.category,
  comments: models.Comment,
};

/* 
 * Initiliase the loader with "includeModels", 
 * a map of all models referenced in GraphQL with their respective Sequelize Model
 */
queryLoader.init({ includeModels });

/**
 * GraphQL
 */
Query: {
  articles: async (parent, args, { models }, info) => {
    const { Article } = models;
    const queryOptions = queryLoader.getFindOptions({ model: Article, info });
    const articles = await Article.findAll(queryOptions);
    return articles;
  },
},

Examples

You can find examples in the demo directory. It contains migrations, models and seeds setup for testing out the app.
It also contains graphql schemas and resolvers with examples of how the queryLoader utility is used

Testing the Demo

On the git repo You can quickly test the demo and play with the code using Gitpod.
Gitpod is a full blown IDE created on the fly from a git repository.
It allows us to test a github project with just the browser. Learn more about gitpod OR install the chrome extension

  • clone the repo, if you want to test locally
  • check into the demo directory. $cd demo
  • environment should be set to development. This is already setup in the package.json scripts
  • setup DATABASE_URL: You can use this database created with elephantsql.
    postgres://cigjzbzt:krzc-48qlH4hfj0HM5Oid_rfxN9uLbuf@raja.db.elephantsql.com:5432/cigjzbzt
  • npm install
  • run migrations and seeds - npm run db:seed (optional): This will create tables and seed them with dummy data. If you are testing the project locally, you will definitely need to this the first time, but if you are testing it online with gitpod, the database has already been migrated and seeded, so you don't have to do this step.
  • start the development server: npm start
  • send GraphQL queries to the /graphql endpoint.

Examples queries

{
  articles(scope: 'id|gt|2') {
    id
    title
  }
}

{
  articles {
    id
    title
    owner {
      firstname
      lastname
    }
    comments {
      id
      body
    }
  }
}

{
  categories {
    name
    articles {
      id
      title
      owner {
        firstname
        lastname
      }
      comments {
        id
        body
      }
    }
  }
}

To get a better view of this utility's value, check the terminal to see the number of queries executed by Sequelize. You will find that all the queries above execute JUST ONE query. This could have been over tens of queries given very large tables, and with code not so well written.

Unit Tests

npm test

You can find the test cases in the /src/__tests__ directory

Scope Argument

This allows us to query models and return records matching certain conditions. Currently, we support a small set of Sequelize operators with the scope argument

Usage

In a GraphQL query, provide scope argument with the following pattern field|operator|value

Example

articles(scope: 'title|like|%graphql%') {
  id
  title
}

Supported Scope Operators

eq, gt, gte, like, lt, lte, ne


Author

Samuel Osuh @jsamchineme

About

A utility for eager-loading related resources based on the structure of a GraphQL Query

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages