kuitos / axios-extensions

🍱 axios extensions lib, including throttle, cache, retry features etc...
MIT License
831 stars 49 forks source link

getting custom cache with promise to get error #62

Closed kivervinicius closed 4 years ago

kivervinicius commented 4 years ago

When using a cache like function, the get method if a promise returns null and no and the error in the axios adapter function.

image

example: this example i use sessionStorage but i use localforage in production

export default {
    async get (index) {
        console.log("get", index);
        const v = sessionStorage.getItem(index);
        return v;
    },
    async set (index, value) {
        const v = await value;
        console.log("set", index, v);
        sessionStorage.setItem(index, JSON.parse(JSON.stringify(v)));
    },
    del (index) {
        console.log("del", index);
        sessionStorage.removeItem(index);
    },
};
kuitos commented 4 years ago

pls provide the detail error stack

kuitos commented 4 years ago

The get function may returns null if it invoked before the value set to sessionStorage until the promise resolved. you may need to combine a memory cache with a persist cache to support your requirement.

kuitos commented 4 years ago

Solution for your requirement:

const map = new Map();

export default {
    async get (index) {
        return map.get(index) || sessionStorage.getItem(index);
    },
    async set (index, value) {
        map.set(index, value);
        const v = await value;
        sessionStorage.setItem(index, JSON.parse(JSON.stringify(v)));
    },
    del (index) {
        console.log("del", index);
        map.delete(index);
        sessionStorage.removeItem(index);
    },
};