index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var LRU_1 = require("./utils/LRU");
  4. var CACHE_SIZE = 1000;
  5. /**
  6. * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache]
  7. */
  8. var EndpointCache = /** @class */ (function () {
  9. function EndpointCache(maxSize) {
  10. if (maxSize === void 0) { maxSize = CACHE_SIZE; }
  11. this.maxSize = maxSize;
  12. this.cache = new LRU_1.LRUCache(maxSize);
  13. }
  14. ;
  15. Object.defineProperty(EndpointCache.prototype, "size", {
  16. get: function () {
  17. return this.cache.length;
  18. },
  19. enumerable: true,
  20. configurable: true
  21. });
  22. EndpointCache.prototype.put = function (key, value) {
  23. var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
  24. var endpointRecord = this.populateValue(value);
  25. this.cache.put(keyString, endpointRecord);
  26. };
  27. EndpointCache.prototype.get = function (key) {
  28. var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
  29. var now = Date.now();
  30. var records = this.cache.get(keyString);
  31. if (records) {
  32. for (var i = records.length-1; i >= 0; i--) {
  33. var record = records[i];
  34. if (record.Expire < now) {
  35. records.splice(i, 1);
  36. }
  37. }
  38. if (records.length === 0) {
  39. this.cache.remove(keyString);
  40. return undefined;
  41. }
  42. }
  43. return records;
  44. };
  45. EndpointCache.getKeyString = function (key) {
  46. var identifiers = [];
  47. var identifierNames = Object.keys(key).sort();
  48. for (var i = 0; i < identifierNames.length; i++) {
  49. var identifierName = identifierNames[i];
  50. if (key[identifierName] === undefined)
  51. continue;
  52. identifiers.push(key[identifierName]);
  53. }
  54. return identifiers.join(' ');
  55. };
  56. EndpointCache.prototype.populateValue = function (endpoints) {
  57. var now = Date.now();
  58. return endpoints.map(function (endpoint) { return ({
  59. Address: endpoint.Address || '',
  60. Expire: now + (endpoint.CachePeriodInMinutes || 1) * 60 * 1000
  61. }); });
  62. };
  63. EndpointCache.prototype.empty = function () {
  64. this.cache.empty();
  65. };
  66. EndpointCache.prototype.remove = function (key) {
  67. var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
  68. this.cache.remove(keyString);
  69. };
  70. return EndpointCache;
  71. }());
  72. exports.EndpointCache = EndpointCache;