Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option to pass in cache key generator fn or value #54

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,83 @@ store.cache.dispatch({
timeout: 30000
});
```

### cache-key-generators

For example, maybe there is something like a per-call request-root-id, but it should not be used in the cache key..
An example to set a globally overridden default cache-key generator function:

```js
/**
* Generate key from Dispatch parameters.
* @param {DispatchParams} params
* @returns {string|Error}
*/
const cacheKeyCreatorFn = function (params) {
console.log('localRootStore:cacheKeyGeneratorFn:', arguments)
try {
const ref = resolveParams(params)
const type = ref[0]
let payload = ref[1]
if (payload) {
if (payload._cacheKey) {
if (ObjectExts.isFunction(payload._cacheKey)) {
// keep using local-cache-key generator:
return payload._cacheKey(type, payload)
} else {
// keep using externally-set cache-key:
return (type + ':' + (toString(payload._cacheKey)))
}
} else if (payload.rrid) {
// remove this from the cache-input:
payload = Object.assign({}, payload)
delete payload.rrid
return (type + ':' + (toString(payload)))
} else {
//go ahead with all params:
return (type + ':' + (toString(payload)))
}
} else {
return (type + ':' + (toString(payload)))
}
} catch (_) {
return GenerateKeyError
}
}

// config, to add generator function:
const cacheOptions = {
// timeout: 10000, // default == 0 == never-evict,
generateKey: cacheKeyCreatorFn
}

// create Store..
const localRootStore = new Vuex.Store({
plugins: [createCache(cacheOptions)],
strict: process.env.NODE_ENV !== 'production'
})
```

To use a fixed cache key, in a store, for this cached call only; passing in other params: (singleton-query..)
But, instead of returning a fixed key, the function could also create key based on the other params..
Usage in the store action:

```js
const actions = {
getDataOnlyOnce: cacheAction(
function({ cache, dispatch }, params) {
let cacheParams = Object.assign({
_cacheKey:function(type, payload){return '$$static_key_here$$'}
}, params);
return cache.dispatch('fetchDataOnlyOnce', cacheParams)
.then(function(singleResponse) {
// ...
})
//...
;
//...
})
)
, //...
}
```
21 changes: 15 additions & 6 deletions src/vuex-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,21 @@ const GenerateKeyError = new Error("Can't generate key from parameters.")
* @param {DispatchParams} params
* @returns {string|Error}
*/
const generateKey = (params) => {
const defaultGenerateKey = function (params) {
try {
const [type, payload] = resolveParams(params)
return `${type}:${toString(payload)}`
const ref = resolveParams(params)
const type = ref[0]
const payload = ref[1]
return (type + ':' + (toString(payload)))
} catch (_) {
return GenerateKeyError
}
}

const configurableGlobal = {
generateKey: defaultGenerateKey
}

/**
* Check if value has timeout property.
* @param {any} value
Expand Down Expand Up @@ -110,14 +116,17 @@ const state = new Map()
* @param {Options} [options]
*/
const defineCache = (store, options) => {
if (options && options.generateKey) {
configurableGlobal.generateKey = options.generateKey
}
const cache = {
/**
* Dispatch an action and set it on cache.
* @param {...DispatchParams} params
* @returns {Promise<any>}
*/
dispatch(...params) {
const key = generateKey(params)
const key = configurableGlobal.generateKey(params)

if (key === GenerateKeyError) {
// Fallback on generateKey errors.
Expand Down Expand Up @@ -151,7 +160,7 @@ const defineCache = (store, options) => {
* @returns {boolean}
*/
has(...params) {
const key = generateKey(params)
const key = configurableGlobal.generateKey(params)

if (key === GenerateKeyError) {
// Fallback on generateKey errors.
Expand Down Expand Up @@ -184,7 +193,7 @@ const defineCache = (store, options) => {
* @returns {boolean}
*/
delete(...params) {
const key = generateKey(params)
const key = configurableGlobal.generateKey(params)

if (key === GenerateKeyError) {
// Fallback on generateKey errors.
Expand Down