validations.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict'
  2. /**
  3. * Validate a topic to see if it's valid or not.
  4. * A topic is valid if it follow below rules:
  5. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  6. * - Rule #2: Part `#` must be located at the end of the mailbox
  7. *
  8. * @param {String} topic - A topic
  9. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  10. */
  11. function validateTopic (topic) {
  12. var parts = topic.split('/')
  13. for (var i = 0; i < parts.length; i++) {
  14. if (parts[i] === '+') {
  15. continue
  16. }
  17. if (parts[i] === '#') {
  18. // for Rule #2
  19. return i === parts.length - 1
  20. }
  21. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  22. return false
  23. }
  24. }
  25. return true
  26. }
  27. /**
  28. * Validate an array of topics to see if any of them is valid or not
  29. * @param {Array} topics - Array of topics
  30. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  31. */
  32. function validateTopics (topics) {
  33. if (topics.length === 0) {
  34. return 'empty_topic_list'
  35. }
  36. for (var i = 0; i < topics.length; i++) {
  37. if (!validateTopic(topics[i])) {
  38. return topics[i]
  39. }
  40. }
  41. return null
  42. }
  43. module.exports = {
  44. validateTopics: validateTopics
  45. }