Created
August 10, 2017 07:06
-
-
Save shanelau/586e0211dffc59b434c9664055dc2d87 to your computer and use it in GitHub Desktop.
egg middle for url cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const DEFAULT_TTL = 60 * 1000; | |
const MIN_10 = 1 * 60 * 1000; | |
const cacheConfig = { | |
'/api/page/index': DEFAULT_TTL, | |
'/api/page/miner': DEFAULT_TTL, | |
'/api/page/luck': DEFAULT_TTL, | |
'/api/page/': DEFAULT_TTL, | |
'/api/blocks': DEFAULT_TTL, | |
'/api/miner/top10': MIN_10, | |
'/api/block/history': MIN_10, | |
'/api/pool/difficultyAvg': MIN_10, | |
'/api/pool/hashrateAvg': MIN_10, | |
}; | |
function needCache(key) { | |
return cacheConfig[key] || false; | |
} | |
/* | |
* 接口 cache, 根据 url 前缀设置 cache | |
* 开发环境不会启用缓存 | |
*/ | |
module.exports = options => { | |
const cachePrefix = 'page:'; | |
return function* cache(next) { | |
if (this.app.config.env !== 'prod' || this.request.query.refresh) { | |
yield next; | |
return; | |
} | |
const key = this.request.originalUrl; | |
const url = key.indexOf('?') > 0 ? this.request.url.split('?')[0] : key; | |
const ttl = needCache(url); | |
if (!ttl) { | |
yield next; | |
} else { | |
const data = yield this.app.redis.getAsync(cachePrefix + key); | |
if (data) { | |
this.logger.info('cached'); | |
this.set('Cache-Control', `max-age=${ttl / 1000}`); | |
this.response.body = data; | |
return; | |
} | |
yield next; | |
if (this.status === 200) { | |
yield this.app.redis.setAsync(cachePrefix + key, JSON.stringify(this.response.body), 'EX', ttl / 1000); | |
} | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment