Skip to content

Use Cache

Sometimes you need to store temporary values such as tokens or deduplication keys, just use jiant.get.cache as follow :

Reference

jiant.get.cache() -> object

Get cache functions: tryGet, get, set.

js
// const { tryGet, get, set } = jiant.get.cache()
const cache = jiant.get.cache()

const tempKey = "custom_temp_key"
const maxExpireAgeInSecond = 3600 // in seconds
const getValueFunc = async ()=>{
    await jiant.action.sleep(1000) // in milliseconds
    // ...
    return 'some_value'
}

// Fetch value with function then save it in cache
let value = await cache.tryGet(tempKey, getValueFunc, maxExpireAgeInSecond)
// output: 'some_value'

// Set value with key
await cache.set(tempKey, 'another_value', maxExpireAgeInSecond)

// Get value with key
value = await cache.get(tempKey)
// ouput: 'another_value'

// Cache will expire after expire time which set when saving.
await jiant.action.sleep(1000 * maxExpireAgeInSecond)
value = await cache.get(tempKey)
// output: null

tryGet(key, getValueFunc, maxAge, renewExpire, forceReload) -> Promise

ParamTypeRequiredDescription
keystringKey to store and fetch cached value
getValueFuncfunctionasync/sync function returns value to be cached when no value existed or previous value expired.
maxAgenumberDefault: 3600. Max age in seconds before value expired.
renewExpirebooleanDefault: false. Whether to renew expiration with maxAge
forceReloadbooleanDefault: false. Whether to ignore current value and reload with getValueFunc.

get(key, renewExpire) -> Promise

set(key, newValue, maxAge) -> Promise