GraphQL Cache

Build Status Test Coverage Maintainability

GraphQL Cache is a custom middleware for graphql-ruby providing field-level caching. It is currently a work in progress and the API is subject to change prior to the release v1.0.0.

Installation

Add this line to your application's Gemfile:

  gem 'graphql-cache'

And then execute:

  $ bundle

Or install it yourself as:

  $ gem install graphql-cache

Setup

  1. Add middleware GraphQL::Cache::Middleware to your schema
  2. Add field_class GraphQL::Cache::Field to your base object type

Configuration

GraphQL Cache can be configured in an initializer:

  # config/initializers/graphql_cache.rb

  GraphQL::Cache.configure do |config|
    config.namespace = 'GraphQL::Cache' # Cache key prefix for keys generated by graphql-cache
    config.cache     = Rails.cache      # The cache object to use for caching
    config.logger    = Rails.logger     # Logger to receive cache-related log messages
    config.expiry    = 5400             # 90 minutes (in seconds)
    config.force     = false            # Cache override, when true no caching takes place
  end

Usage

Any object, list, or connection field can be cached by simply adding cache: true to the field definition:

  field :calculated_field, Int, cache: true

By default all keys will have an expiration of GraphQL::Cache.expiry which defaults to 90 minutes. If you want to set a field-specific expiration time pass a hash to the cache parameter like this:

  field :calculated_field, Int, cache: { expiry: 10800 } # expires key after 180 minutes

When passing a hash in the cache parameter the possible options are:

  • expiry: expiration time for this field's key in seconds (default: 5400)
  • force: for cache misses on this field (default: false)
  • prefix: cache key prefix (appended after GraphQL::Cache.namespace)

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/Leanstack/graphql-cache. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Graphql::Cache project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.