Skip to content

caching data

kapil verma edited this page Jul 1, 2019 · 2 revisions

title: Caching Data

Caching Data

If you have provided a redis-config on initializing tabel ORM, each table-object will have a cache property associated with it, which is just a namespaced key-value store implemented over redis. Details Below:


cache.set

table(...).cache.set(key, val, lifetime)

returns Promise.

Arguments:

  1. key: String key against which a value will be stored.
  2. val: Value to be stored. Best to use only plain JS objects and arrays.
  3. lifetime: Lifetime of the cache in milliseconds.

Usage:

const posts = await table('posts').where(...).all();

await table('posts').cache.set('someUniqueKey', posts)

cache.get

table(...).cache.get(key, defaultValue=null)

returns Promise which resolves to the value stored against the key, and to defaultValue in case of there isn't any value stored against the key.

Arguments:

  1. key: String key which will be used to fetch value from cache.
  2. defaultValue: Value to return in case of no cached-value is found against key.

Usage:

const posts = await table('posts').cache.get('someUniqueKey', []);

cache.delete

table(...).cache.delete(key)

table(...).cache.del(key) shorthand

returns Promise.

Arguments:

  1. key: String key which will be deleted from the cache.

Usage:

await table('posts').cache.delete('someUniqueKey');

cache.clear

table(...).cache.clear()

return Promise. Clears all keys stored in the cache.

Usage:

await table('posts').cache.clear();

Caching Query Chains

As of version 2.6.0, tabel ORM offers a pretty nifty feature related to caching, which is caching/cache-busting query chains.You can use this feature for caching selected query chains, and busting them as needed. Example below:

function postsQueryWithSeveralJoins() {
  return table('posts')
    .author().join()
    .comments().leftJoin()
    .tags().leftJoin()
    .where('is_published', true)
  ;
}

async function getPosts() {
  return await postsQueryWithSeveralJoins().remember(3000).all();
  // the above code will cache the results of the query for 3000 ms,
  // after which results of the query will be renewed in the cache.
}

async function forgetPosts() {
  return await postsQueryWithSeveralJoins().forget();
  // busts the cache for the query.
}

Next > ORM Exports