Skip to content

Commit

Permalink
Add remember function method
Browse files Browse the repository at this point in the history
  • Loading branch information
sdvcrx committed Aug 27, 2017
1 parent 99ddd91 commit 1c6b5bd
Showing 1 changed file with 46 additions and 5 deletions.
51 changes: 46 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,66 @@ const CacheDriver = require('./redisCacheDriver')

const Cache = {}

Cache.remember = function remember (key, timeout = 0, promise) {
function serializeArguments(obj) {
return Array
.from(obj)
.map(val => JSON.stringify(val))
.join('-')
}

Cache.rememberFunc = function rememberFunc (key, func) {
return function () {
return new Promise((resolve, reject) => {
const cacheKey = `${key}-${serializeArguments(arguments)}`

CacheDriver.get(cacheKey).then((cacheData) => {
if (cacheData.invalid()) {
func.apply(this, arguments).then((data) => {
// cache data
CacheDriver.set(cacheKey, data)

resolve(data)
}).catch(err => reject(err))
} else {
resolve(cacheData.data)
}
})
})
}
};

/**
* Cache promise result
*
* @param {String} key
* @param {Number} timeout seconds
* @param {Function} funcReturnPromise function that return a promise
*/
Cache.remember = function remember (key, timeout = 0, funcReturnPromise) {
return new Promise((resolve, reject) => {
CacheDriver.get(key).then((cacheData) => {
if (cacheData.invalid()) {
promise.then((data) => {
lazyPromise().then((data) => {
// cache data
CacheDriver.set(key, data)

resolve(data)
})
}).catch(err => reject(err))
} else {
resolve(cacheData.data)
}
})
})
}

Cache.rememberForever = function rememberForever (key, promise) {
return Cache.remember(key, 0, promise)
/**
* Cache promise result permanently
*
* @param {String} key
* @param {Function} funcReturnPromise function that return a promise
*/
Cache.rememberForever = function rememberForever (key, funcReturnPromise) {
return Cache.remember(key, 0, funcReturnPromise)
}

module.exports = Cache

0 comments on commit 1c6b5bd

Please sign in to comment.