redis.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const redis = require("redis");
  4. const loggers_1 = require("./loggers");
  5. const logger = loggers_1.getLogger('redis');
  6. class default_1 {
  7. constructor(opt) {
  8. this.chatAsString = (chat) => `${chat.chatType}:${chat.chatID.toString()}`;
  9. this.cacheContent = (contentId, content) => new Promise((resolve, reject) => this.client.set(`content/${contentId}`, content, 'EX', 3600 * 24, (err, res) => err ? reject(err) : resolve(res))).then(res => {
  10. logger.debug(`cached content ${contentId}, result: ${res}`);
  11. }).catch((err) => {
  12. logger.error(`failed to cache content ${contentId}, error: ${err}`);
  13. });
  14. this.cacheForChat = (postId, target) => {
  15. const targetStr = this.chatAsString(target);
  16. return new Promise((resolve, reject) => this.client.set(`sent/${targetStr}/${postId}`, 'true', 'EX', this.expireAfter, (err, res) => err ? reject(err) : resolve(res))).then(res => {
  17. logger.debug(`cached post ${postId} for ${targetStr}, result: ${res}`);
  18. }).catch((err) => {
  19. logger.error(`failed to cache post ${postId} for ${targetStr}, error: ${err}`);
  20. });
  21. };
  22. this.getContent = (contentId) => new Promise((resolve, reject) => this.client.get(`content/${contentId}`, (err, res) => err ? reject(err) : resolve(res))).then(res => {
  23. logger.debug(`retrieved cached content ${contentId}, result: ${res}`);
  24. return res;
  25. }).catch((err) => {
  26. logger.error(`failed to retrieve cached content ${contentId}, error: ${err}`);
  27. throw err;
  28. });
  29. this.isCachedForChat = (postId, target) => {
  30. const targetStr = this.chatAsString(target);
  31. return new Promise((resolve, reject) => this.client.exists(`sent/${targetStr}/${postId}`, (err, res) => err ? reject(err) : resolve(res))).then(res => {
  32. logger.debug(`retrieved status of post ${postId} for ${targetStr}, result: ${res}`);
  33. return Boolean(res);
  34. }).catch((err) => {
  35. logger.error(`failed to retrieve status of post ${postId} for ${targetStr}, error: ${err}`);
  36. return false;
  37. });
  38. };
  39. this.client = redis.createClient({
  40. host: opt.redisHost,
  41. port: opt.redisPort,
  42. });
  43. this.expireAfter = opt.redisExpireTime;
  44. logger.info(`loaded redis service at ${opt.redisHost}:${opt.redisPort}`);
  45. }
  46. }
  47. exports.default = default_1;
  48. //# sourceMappingURL=redis.js.map