1. /**
  2. * Represents a given version string in a comparable manor.
  3. *
  4. * @class
  5. * @author Frank Villasenor
  6. * @param strVersion dbVersion as a string. 1.0.0 or 1.0.0.1
  7. * @constructor
  8. */
  9. function dbVersion(strVersion) {
  10. this.original = strVersion;
  11. const parsed = strVersion.match(/(\d+)\.(\d+)\.(\d+)\.*(\d*)/);
  12. this.debug = require('debug')('db-migration:dbVersion');
  13. this.parsed = Object.freeze({
  14. major: parseInt(parsed[1]),
  15. minor: parseInt(parsed[2]),
  16. revision: parseInt(parsed[3]),
  17. build: parseInt(parsed[4] || 0)
  18. });
  19. this.debug("parsed", this.parsed);
  20. }
  21. /**
  22. * Compares me against another dbVersion instance.
  23. * Equal: 0
  24. * this newer: 1
  25. * other newer: -1
  26. * @param other The other instance to compare against.
  27. * @returns {number} 0=Equals; 1=this newer; -1=other newer
  28. */
  29. dbVersion.prototype.compare = function (other) {
  30. this.debug('other', other);
  31. if (typeof other !== 'object' && typeof other.parsed !== 'object') throw "Invalid input";
  32. try {
  33. const weAreEqual = (this.parsed.major == other.parsed.major) &&
  34. (this.parsed.minor == other.parsed.minor) &&
  35. (this.parsed.revision == other.parsed.revision) &&
  36. (this.parsed.build == other.parsed.build);
  37. if (weAreEqual) return 0;
  38. if (this.amNewer(other)) return 1;
  39. return -1;
  40. } catch (er) {
  41. this.debug("Error in compare", er, parsed_version, other);
  42. throw er;
  43. }
  44. };
  45. /**
  46. * Is this instance newer (greater) than the given 'other' instance
  47. * @param other
  48. * @returns {boolean}
  49. */
  50. dbVersion.prototype.amNewer = function (other) {
  51. return (this.parsed.major > other.parsed.major) ||
  52. (this.parsed.minor > other.parsed.minor) ||
  53. (this.parsed.revision > other.parsed.revision) ||
  54. (this.parsed.build > other.parsed.build);
  55. //need to handle build
  56. };
  57. module.exports = dbVersion;