Skip to content

Commit

Permalink
Add cache callback
Browse files Browse the repository at this point in the history
  • Loading branch information
vencakrecl committed Jan 29, 2021
1 parent fc16bf1 commit 273ad76
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 8 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@

### How to install
```bash
npm install vuex-simple-cache
npm install @vencakrecl/vuex-simple-cache
```
```bash
yarn add vuex-simple-cache
yarn add @vencakrecl/vuex-simple-cache
```

### How to use
```js
import Vue from 'vue';
import Vuex, { Store } from 'vuex';
import VuexSimpleCache from 'vuex-simple-cache';
import VuexSimpleCache from '@vencakrecl/vuex-simple-cache';

Vue.use(Vuex);

Expand Down Expand Up @@ -53,6 +53,7 @@ store.registerModule('test', {
* key - name of key from vuex state
* action - standard vuex action
* expiration - time in seconds
* onCache - callback for cached data (default return cached data)

[npm]: https://img.shields.io/npm/v/@vencakrecl/vuex-simple-cache.svg?style=flat-square
[license]: https://img.shields.io/npm/l/@vencakrecl/vuex-simple-cache.svg?style=flat-square
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "@vencakrecl/vuex-simple-cache",
"author": "Venca Krecl <[email protected]>",
"description": "Simple cache for vuex action",
"version": "1.0.0-alpha.9",
"version": "1.0.0-beta.0",
"license": "MIT",
"repository": {
"type": "git",
Expand All @@ -27,6 +27,7 @@
"build": "tsdx build",
"test": "tsdx test",
"lint": "tsdx lint",
"lint-fix": "tsdx lint --fix",
"prepare": "tsdx build",
"size": "size-limit",
"analyze": "size-limit --why",
Expand Down
11 changes: 7 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ class VuexSimpleCache {
public cacheAction = <S extends Record<string, any>, R>(
key: string,
action: (context: ActionContext<S, R>) => any,
expiration: number = 0
expiration: number = 30,
onCache: (context: ActionContext<S, R>, data: any) => any = (_, data) => {
return data;
}
): any => {
return (context: ActionContext<S, R>) => {
if (!(key in context.state)) {
Expand All @@ -31,22 +34,22 @@ class VuexSimpleCache {

if (Array.isArray(context.state[key])) {
if (context.state[key].length) {
return context.state[key];
return onCache(context, context.state[key]);
}

return action(context);
}

if (context.state[key] instanceof Object) {
if (Object.keys(context.state[key]).length) {
return context.state[key];
return onCache(context, context.state[key]);
}

return action(context);
}

if (context.state[key]) {
return context.state[key];
return onCache(context, context.state[key]);
}

return action(context);
Expand Down

0 comments on commit 273ad76

Please sign in to comment.