Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. /**
  2. * Create method which can be throttled in different ways using redis cache
  3. */
  4. 'use strict'
  5.  
  6. // global-level options
  7. const defaultConfig = {
  8. redis: null, // redis instance (required)
  9. key: 'cache', // global redis key
  10. ttl: null // global ttl value
  11. }
  12.  
  13. // .wrap method options
  14. const defaultWrapConfig = {
  15. hash: null, // local redis key
  16. ttl: null // cache ttl
  17. }
  18.  
  19. class Cache {
  20. constructor(cfg, redis) {
  21. this.cfg = Object.assign({}, defaultConfig, cfg)
  22. this.redis = redis || this.cfg.redis
  23. if (!this.redis) {
  24. throw new Error('please provide cfg.redis instance')
  25. }
  26. }
  27.  
  28. flush(hash) {
  29. const redisKey = this.redisKey(hash)
  30. return this.redis.del(redisKey)
  31. }
  32.  
  33. redisKey(hash) {
  34. return `${hash}::${this.cfg.key}`
  35. }
  36.  
  37. /**
  38. * Return wrapped method which execute payload and cache result
  39. */
  40. wrap(payload, opt) {
  41. const cfg = Object.assign({}, defaultWrapConfig, opt)
  42. const ttl = cfg.ttl || this.cfg.ttl
  43. if (!cfg.hash) {
  44. throw new Error('please specify wrap.cfg.hash')
  45. }
  46. const redisKey = this.redisKey(cfg.hash)
  47. const redis = this.redis
  48.  
  49. return function wrappedMethod() {
  50. const payloadArgs = arguments
  51. let isCacheExists = false
  52. return Promise.resolve().then(() => {
  53. // test existing cache
  54. return redis.get(redisKey).then(res => {
  55. isCacheExists = (res !== null)
  56. return JSON.parse(res)
  57. })
  58. }).then(data => {
  59. // execute payload
  60. if (isCacheExists) {
  61. return data
  62. }
  63. return payload.apply(null, payloadArgs).then(res => {
  64. const cacheArgs = [redisKey, JSON.stringify(res)]
  65. if (ttl) {
  66. cacheArgs.push('PX', ttl)
  67. }
  68. return redis.set.apply(redis, cacheArgs).then(() => res)
  69. })
  70. })
  71. }
  72. }
  73. }
  74.  
  75. module.exports = Cache
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement