Grind’s Cache provider integrates Grind with cache-manager.
You can access cache via app.cache
.
First, add the grind-cache
package via your preferred package manager:
yarn add grind-cache
Next, you’ll need to add CacheProvider
to your app providers in app/Boostrap.js
:
const app =appproviders
grind-cache
is included as part ofgrind-core
andgrind-core-frontend
. If you’re using one of these bundle packages, you don’t need to explicitly add thegrind-cache
package.
To retrieve a value from the cache, call cache.get(key)
. It will return a promise that will resolve with the value, or null if it doesn’t exist.
appcache
To cache a value in the store, call cache.set(key, value)
. It will return a promise that resolves once it’s been stored.
appcache
The third { ttl }
parameter is optional, if you don’t pass it, it uses the default value as defined in your config.
Cache also has a convenient cache.wrap(key, retreiver)
function that will first try to read the key from the cache, and if it’s missing, call the retreiver and store it.
appcache
The third { ttl }
parameter is optional, if you don’t pass it, it uses the default value as defined in your config.
To remove a cached value from the store, call cache.del(key)
. It will return a promise that resolves once it’s been removed.
appcache
By default, only in-memory is supported. If you wish to persist cache (or share between other instances), you’ll want to install a different engine.
cache-manager supports a variety of engines, including fs, redis and memcache:
yarn add cache-manager-redisyarn add cache-manager-mongodbyarn add cache-manager-mongooseyarn add cache-manager-fsyarn add cache-manager-fs-binaryyarn add cache-manager-memcached-store
Your cache config should live in /config/cache.json
.
Here’s an example of a config file showing support for memory, fs and redis:
The default
key tells the Cache provider which store it configure app.cache
to use.
If you wish to access the non-default cache store, you can load it via the Cache
function.
const store =
The first parameter passed to Cache()
is the store. This can either be the name of a store in your cache.json
config file, or you can pass in a full config object.
The second parameter passed to Cache()
is the instance of app. If you pass a config object, the app instance is not required.