topic-alias-recv.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict'
  2. /**
  3. * Topic Alias receiving manager
  4. * This holds alias to topic map
  5. * @param {Number} [max] - topic alias maximum entries
  6. */
  7. function TopicAliasRecv (max) {
  8. if (!(this instanceof TopicAliasRecv)) {
  9. return new TopicAliasRecv(max)
  10. }
  11. this.aliasToTopic = {}
  12. this.max = max
  13. }
  14. /**
  15. * Insert or update topic - alias entry.
  16. * @param {String} [topic] - topic
  17. * @param {Number} [alias] - topic alias
  18. * @returns {Boolean} - if success return true otherwise false
  19. */
  20. TopicAliasRecv.prototype.put = function (topic, alias) {
  21. if (alias === 0 || alias > this.max) {
  22. return false
  23. }
  24. this.aliasToTopic[alias] = topic
  25. this.length = Object.keys(this.aliasToTopic).length
  26. return true
  27. }
  28. /**
  29. * Get topic by alias
  30. * @param {String} [topic] - topic
  31. * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined
  32. */
  33. TopicAliasRecv.prototype.getTopicByAlias = function (alias) {
  34. return this.aliasToTopic[alias]
  35. }
  36. /**
  37. * Clear all entries
  38. */
  39. TopicAliasRecv.prototype.clear = function () {
  40. this.aliasToTopic = {}
  41. }
  42. module.exports = TopicAliasRecv