coaobject.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /* eslint-disable class-methods-use-this */
  2. 'use strict';
  3. const Q = require('q');
  4. /**
  5. * COA Object
  6. *
  7. * Base class for all COA-related objects
  8. *
  9. * --------|-----|-----|-----
  10. * | Cmd | Opt | Arg
  11. * --------|-----|-----|-----
  12. * name | ✓ | ✓ | ✓
  13. * title | ✓ | ✓ | ✓
  14. * comp | ✓ | ✓ | ✓
  15. * reject | ✓ | ✓ | ✓
  16. * end | ✓ | ✓ | ✓
  17. * apply | ✓ | ✓ | ✓
  18. *
  19. * @class CoaObject
  20. */
  21. module.exports = class CoaObject {
  22. constructor(cmd) {
  23. this._cmd = cmd;
  24. this._name = null;
  25. this._title = null;
  26. this._comp = null;
  27. }
  28. /**
  29. * Set a canonical identifier to be used anywhere in the API.
  30. *
  31. * @param {String} name - command, option or argument name
  32. * @returns {COA.CoaObject} - this instance (for chainability)
  33. */
  34. name(name) {
  35. this._name = name;
  36. return this;
  37. }
  38. /**
  39. * Set a long description to be used anywhere in text messages.
  40. * @param {String} title - human readable entity title
  41. * @returns {COA.CoaObject} - this instance (for chainability)
  42. */
  43. title(title) {
  44. this._title = title;
  45. return this;
  46. }
  47. /**
  48. * Set custom additional completion for current object.
  49. *
  50. * @param {Function} comp - completion generation function,
  51. * invoked in the context of object instance.
  52. * Accepts parameters:
  53. * - {Object} opts - completion options
  54. * It can return promise or any other value threated as a result.
  55. * @returns {COA.CoaObject} - this instance (for chainability)
  56. */
  57. comp(comp) {
  58. this._comp = comp;
  59. return this;
  60. }
  61. /**
  62. * Apply function with arguments in a context of object instance.
  63. *
  64. * @param {Function} fn - body
  65. * @param {Array.<*>} args... - arguments
  66. * @returns {COA.CoaObject} - this instance (for chainability)
  67. */
  68. apply(fn) {
  69. arguments.length > 1?
  70. fn.apply(this, [].slice.call(arguments, 1))
  71. : fn.call(this);
  72. return this;
  73. }
  74. /**
  75. * Return reject of actions results promise with error code.
  76. * Use in .act() for return with error.
  77. * @param {Object} reason - reject reason
  78. * You can customize toString() method and exitCode property
  79. * of reason object.
  80. * @returns {Q.promise} rejected promise
  81. */
  82. reject(reason) {
  83. return Q.reject(reason);
  84. }
  85. /**
  86. * Finish chain for current subcommand and return parent command instance.
  87. * @returns {COA.Cmd} parent command
  88. */
  89. end() {
  90. return this._cmd;
  91. }
  92. };