Skip to content

Instantly share code, notes, and snippets.

@tomasreichmann
Created October 18, 2018 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomasreichmann/c7e1e5af798a192db9c750591099b64f to your computer and use it in GitHub Desktop.
Save tomasreichmann/c7e1e5af798a192db9c750591099b64f to your computer and use it in GitHub Desktop.
({ babel: false})
const set = require('lodash/set');
const get = require('lodash/get');
const unset = require('lodash/unset');
// Mocks ===
const mockPromise = (response = 123, delay = 1000, willFail = false) => {
return new Promise((resolve, reject) => {
setTimeout(() => (willFail ? reject(response) : resolve(response)), delay);
});
};
const getTestData = () => {
console.log('getTestData');
return mockPromise();
}
const failGettingTestData = () => {
return mockPromise(undefined, undefined, true);
}
// === Mocks
const cache = {
test: {
a: mockPromise('DATA IN CACHE')
}
};
const NOT_IN_CACHE = 'NOT_IN_CACHE';
const FAILED = 'NOT_IN_CACHE';
const setChachedData = (path, setterPromise) => {
set(cache, path, setterPromise);
return setterPromise.catch((error) => {
deleteFromChache(path);
return Promise.reject(error)
});
};
const deleteFromChache = (path) => {
unset(cache, path);
};
const getCachedData = (path, setter) => {
console.log('getCachedData at', path );
const cachePointer = get(cache, path);
if (cachePointer) {
return cachePointer;
}
if (setter) {
return setChachedData(path, setter())
}
return Promise.reject(NOT_IN_CACHE);
}
const success = (data) => {
console.log('success', data);
console.log('cache', cache);
};
const fail = (error) => {
console.log('fail', error);
console.log('cache', cache);
};
const test = async () => {
await getCachedData(['test', 'a']).then(success, fail); // DATA IN CACHE already
await getCachedData(['test', 'b']).then(success, fail); // data NOT IN CACHE and no setter provided
await getCachedData(['test', 'c'], failGettingTestData).then(success, fail); // fail getting data and
getCachedData(['test', 'd'], getTestData).then(success, fail); // succeed getting data
getCachedData(['test', 'e'], getTestData).then(success, fail); // use the previous promise, getTestData should be only called once
};
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment