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