-
Notifications
You must be signed in to change notification settings - Fork 2
caching data
kapil verma edited this page Jul 1, 2019
·
2 revisions
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:
returns Promise
.
Arguments:
-
key
: String key against which a value will be stored. -
val
: Value to be stored. Best to use only plain JS objects and arrays. -
lifetime
: Lifetime of the cache in milliseconds.
Usage:
const posts = await table('posts').where(...).all();
await table('posts').cache.set('someUniqueKey', posts)
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:
-
key
: String key which will be used to fetch value from cache. -
defaultValue
: Value to return in case of no cached-value is found againstkey
.
Usage:
const posts = await table('posts').cache.get('someUniqueKey', []);
returns Promise
.
Arguments:
-
key
: String key which will be deleted from the cache.
Usage:
await table('posts').cache.delete('someUniqueKey');
return Promise
. Clears all keys stored in the cache.
Usage:
await table('posts').cache.clear();
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.
}