vrack2-core 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,10 +9,18 @@ VRack2 Core
9
9
 
10
10
  --------
11
11
 
12
+ ### Последнее обновление 1.0.4
12
13
 
13
- ### Последнее обновление 1.0.2
14
+ - `BasicType` (класс `Rule`) `require()` deprecated - используем `required()`
15
+ - **ErrorManager** - Теперь не создаёт ошибку при повторной регистрации с одинаковыми параметрами
16
+ - Добавлены методы в **ErrorManager**
17
+ - isCode(error: any, code: string) - Проверяет является ли ошибка VRack2 Error и соответсвует ли код переданной ошибке (проверяет vShort и vCode)
18
+ - isError(error: any) - Проверяет - пренадлежит ли объект ошибки CoreError
14
19
 
15
- - Откат от валидации в `DeviceManager.getDeviceInfo()`
20
+ ### Обновление 1.0.3
21
+
22
+ - Теперь порты `DevicePort` имеют ссылки на устройство своего владельца `Device`
23
+ - Добавлено свойство meta внутри контейнера для хранения дополнительной информации
16
24
 
17
25
  **Использовать эту документацию имеет смысл только для более глубокого изучения устройства VRack2 или для создания сервиса независимого от VRack2**
18
26
 
@@ -86,6 +86,12 @@ export default class Container extends EventEmitter {
86
86
  * @see fillConfFile()
87
87
  * */
88
88
  confFile?: string;
89
+ /**
90
+ * Дополнительные метаданные
91
+ */
92
+ meta?: {
93
+ [key: string]: any;
94
+ };
89
95
  /**
90
96
  * Container bootstrap class
91
97
  *
package/lib/Container.js CHANGED
@@ -368,7 +368,7 @@ class Container extends events_1.default {
368
368
  this.checkPortName(subkey);
369
369
  const handler = ImportManager_1.default.camelize('input.' + subkey);
370
370
  this.checkInputHandler(subkey, handler, dev);
371
- const ndp = new DevicePort_1.default(subkey, pList[subkey]);
371
+ const ndp = new DevicePort_1.default(subkey, pList[subkey], dev);
372
372
  dev.ports.input[subkey] = ndp;
373
373
  // add structure device input ports
374
374
  this.structure[dconf.id].inputs[subkey] = [];
@@ -384,7 +384,7 @@ class Container extends events_1.default {
384
384
  const pList = this.getPortList(key, exp);
385
385
  for (const subkey in pList) {
386
386
  this.checkPortName(subkey);
387
- const ndp = new DevicePort_1.default(subkey, pList[subkey]);
387
+ const ndp = new DevicePort_1.default(subkey, pList[subkey], dev);
388
388
  dev.ports.output[subkey] = ndp;
389
389
  // add structure device output ports
390
390
  this.structure[dconf.id].outputs[subkey] = [];
@@ -34,6 +34,18 @@ declare class ErrorManager {
34
34
  * @param error Ошибка для преобразования
35
35
  */
36
36
  convert(error: any): any;
37
+ /**
38
+ * Проверяет является ли ошибка VRack2 Error
39
+ * и соответсвует ли код переданной ошибке (проверяет vShort и vCode)
40
+ */
41
+ isCode(error: any, code: string): boolean;
42
+ /**
43
+ * Проверяет - пренадлежит объект ошибки VRack2 Error
44
+ *
45
+ * Это не обязательно должен быть класс CoreError но и
46
+ * любой сериализированный класс ошибки VRack2
47
+ */
48
+ isError(error: any): boolean;
37
49
  /**
38
50
  * Searches for an error by code or short
39
51
  *
@@ -31,8 +31,15 @@ class ErrorManager {
31
31
  register(name, code, short, description, rules = {}) {
32
32
  const reg1 = this.getRegistered(code);
33
33
  const reg2 = this.getRegistered(short);
34
- if (reg1 !== null || reg2 !== null)
35
- throw this.make('EM_CODE_EXISTS', { code, short });
34
+ if (reg1 !== null || reg2 !== null) {
35
+ // Если уже есть идентичная запись - просто игнорим
36
+ if ((reg1 === null || reg1 === void 0 ? void 0 : reg1.code) === (reg2 === null || reg2 === void 0 ? void 0 : reg2.code) && (reg1 === null || reg1 === void 0 ? void 0 : reg1.short) === (reg2 === null || reg2 === void 0 ? void 0 : reg2.short)) {
37
+ return;
38
+ }
39
+ else {
40
+ throw this.make('EM_CODE_EXISTS', { code, short });
41
+ }
42
+ }
36
43
  const nr = { name, code, short, description, rules };
37
44
  this.registeredList.push(nr);
38
45
  }
@@ -66,6 +73,30 @@ class ErrorManager {
66
73
  ne.import(error);
67
74
  return ne;
68
75
  }
76
+ /**
77
+ * Проверяет является ли ошибка VRack2 Error
78
+ * и соответсвует ли код переданной ошибке (проверяет vShort и vCode)
79
+ */
80
+ isCode(error, code) {
81
+ if (!this.isError(error))
82
+ return false;
83
+ if (error.vShort === code || error.vCode === code)
84
+ return true;
85
+ return false;
86
+ }
87
+ /**
88
+ * Проверяет - пренадлежит объект ошибки VRack2 Error
89
+ *
90
+ * Это не обязательно должен быть класс CoreError но и
91
+ * любой сериализированный класс ошибки VRack2
92
+ */
93
+ isError(error) {
94
+ if (error instanceof CoreError_1.default)
95
+ return true;
96
+ if (error.vError && error.vCode !== undefined && error.vShort !== undefined)
97
+ return true;
98
+ return false;
99
+ }
69
100
  /**
70
101
  * Searches for an error by code or short
71
102
  *
@@ -79,7 +110,7 @@ class ErrorManager {
79
110
  }
80
111
  }
81
112
  const GlobalErrorManager = new ErrorManager();
82
- GlobalErrorManager.register('ErrorManager', 'NcZIb9QvQRcq', 'EM_CODE_EXISTS', 'This code already exists');
113
+ GlobalErrorManager.register('ErrorManager', 'NcZIb9QvQRcq', 'EM_CODE_EXISTS', 'Has anyone else encountered this error code? Possible duplication of the error code and short word in different registrations.');
83
114
  GlobalErrorManager.register('ErrorManager', 'uLYv4mE1Yo50', 'EM_CODE_NOT_FOUND', 'No such error found');
84
115
  GlobalErrorManager.register('ErrorManager', 'RIl3BUrxWOzP', 'EM_ERROR_CONVERT', 'Converted error');
85
116
  exports.default = GlobalErrorManager;
@@ -1,5 +1,6 @@
1
1
  import IPort from "../ports/IPort";
2
2
  import DeviceConnect from "./DeviceConnect";
3
+ import Device from "./Device";
3
4
  /**
4
5
  * A class to implement a device port.
5
6
  * The port can be either incoming or outgoing
@@ -15,13 +16,15 @@ export default class DevicePort {
15
16
  type: string;
16
17
  /** Flag determines whether the port should be connected */
17
18
  required: boolean;
19
+ /** Ссылка на устройсто владельца */
20
+ Device: Device;
18
21
  /**
19
22
  * Список слушателей порта
20
23
  * Используется для захвата порта. Если какие либо данные будут проброшены
21
24
  * в порт, они будут переданы для каждого вызнванного слушателя
22
25
  */
23
26
  listens: Map<number, (data: any) => void>;
24
- constructor(id: string, port: IPort);
27
+ constructor(id: string, port: IPort, device: Device);
25
28
  /**
26
29
  * Adding communication to a port
27
30
  */
@@ -13,7 +13,7 @@ const Utility_1 = __importDefault(require("../Utility"));
13
13
  * The port can be either incoming or outgoing
14
14
  */
15
15
  class DevicePort {
16
- constructor(id, port) {
16
+ constructor(id, port, device) {
17
17
  /** Flag to determine if the port is connected */
18
18
  this.connected = false;
19
19
  /** Port connection list. One port can have multiple connections */
@@ -27,6 +27,7 @@ class DevicePort {
27
27
  this.id = id;
28
28
  this.type = port.type;
29
29
  this.required = port.required;
30
+ this.Device = device;
30
31
  }
31
32
  /**
32
33
  * Adding communication to a port
@@ -2,6 +2,12 @@ import IValidationRule from "../IValidationRule";
2
2
  export default class BasicType {
3
3
  protected rule: IValidationRule;
4
4
  constructor();
5
+ required(): this;
6
+ /**
7
+ * Вскоре будет удален
8
+ * @see required
9
+ * @deprecated use required()
10
+ */
5
11
  require(): this;
6
12
  /**
7
13
  * Example of a valid value for this rule
@@ -20,6 +20,15 @@ class BasicType {
20
20
  message: '',
21
21
  };
22
22
  }
23
+ required() {
24
+ this.rule.require = true;
25
+ return this;
26
+ }
27
+ /**
28
+ * Вскоре будет удален
29
+ * @see required
30
+ * @deprecated use required()
31
+ */
23
32
  require() {
24
33
  this.rule.require = true;
25
34
  return this;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vrack2-core",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Фреймворк для создания событийно-ориентированных сервисов на JavaScript/TypeScript",
5
5
  "main": "./lib/index",
6
6
  "scripts": {},
package/src/Container.ts CHANGED
@@ -173,6 +173,11 @@ export default class Container extends EventEmitter {
173
173
  * */
174
174
  confFile?: string
175
175
 
176
+ /**
177
+ * Дополнительные метаданные
178
+ */
179
+ meta?: {[key: string]: any}
180
+
176
181
  /**
177
182
  * Container bootstrap class
178
183
  *
@@ -462,7 +467,7 @@ export default class Container extends EventEmitter {
462
467
  this.checkPortName(subkey)
463
468
  const handler = ImportManager.camelize('input.' + subkey) as keyof Device
464
469
  this.checkInputHandler(subkey, handler, dev)
465
- const ndp = new DevicePort(subkey, pList[subkey])
470
+ const ndp = new DevicePort(subkey, pList[subkey], dev)
466
471
  dev.ports.input[subkey] = ndp
467
472
  // add structure device input ports
468
473
  this.structure[dconf.id].inputs[subkey] = []
@@ -480,7 +485,7 @@ export default class Container extends EventEmitter {
480
485
  const pList = this.getPortList(key, exp)
481
486
  for (const subkey in pList) {
482
487
  this.checkPortName(subkey)
483
- const ndp = new DevicePort(subkey, pList[subkey])
488
+ const ndp = new DevicePort(subkey, pList[subkey], dev)
484
489
  dev.ports.output[subkey] = ndp
485
490
  // add structure device output ports
486
491
  this.structure[dconf.id].outputs[subkey] = []
@@ -49,7 +49,14 @@ class ErrorManager {
49
49
  register(name: string, code: string, short: string, description: string, rules: { [key: string]: BasicType } = {}) {
50
50
  const reg1 = this.getRegistered(code)
51
51
  const reg2 = this.getRegistered(short)
52
- if (reg1 !== null || reg2 !== null) throw this.make('EM_CODE_EXISTS', { code, short })
52
+ if (reg1 !== null || reg2 !== null) {
53
+ // Если уже есть идентичная запись - просто игнорим
54
+ if (reg1?.code === reg2?.code && reg1?.short === reg2?.short){
55
+ return
56
+ }else {
57
+ throw this.make('EM_CODE_EXISTS', { code, short })
58
+ }
59
+ }
53
60
  const nr = { name, code, short, description, rules }
54
61
  this.registeredList.push(nr)
55
62
  }
@@ -74,6 +81,7 @@ class ErrorManager {
74
81
  return Object.assign(ne, additional)
75
82
  }
76
83
 
84
+
77
85
  /**
78
86
  * Converts a normal error to a VRack error
79
87
  *
@@ -86,6 +94,28 @@ class ErrorManager {
86
94
  return ne
87
95
  }
88
96
 
97
+ /**
98
+ * Проверяет является ли ошибка VRack2 Error
99
+ * и соответсвует ли код переданной ошибке (проверяет vShort и vCode)
100
+ */
101
+ isCode(error: any, code: string){
102
+ if (!this.isError(error)) return false
103
+ if (error.vShort === code || error.vCode === code) return true
104
+ return false
105
+ }
106
+
107
+ /**
108
+ * Проверяет - пренадлежит объект ошибки VRack2 Error
109
+ *
110
+ * Это не обязательно должен быть класс CoreError но и
111
+ * любой сериализированный класс ошибки VRack2
112
+ */
113
+ isError(error: any){
114
+ if (error instanceof CoreError) return true
115
+ if (error.vError && error.vCode !== undefined && error.vShort !== undefined) return true
116
+ return false
117
+ }
118
+
89
119
  /**
90
120
  * Searches for an error by code or short
91
121
  *
@@ -100,7 +130,7 @@ class ErrorManager {
100
130
 
101
131
 
102
132
  const GlobalErrorManager = new ErrorManager()
103
- GlobalErrorManager.register('ErrorManager', 'NcZIb9QvQRcq', 'EM_CODE_EXISTS', 'This code already exists')
133
+ GlobalErrorManager.register('ErrorManager', 'NcZIb9QvQRcq', 'EM_CODE_EXISTS', 'Has anyone else encountered this error code? Possible duplication of the error code and short word in different registrations.')
104
134
  GlobalErrorManager.register('ErrorManager', 'uLYv4mE1Yo50', 'EM_CODE_NOT_FOUND', 'No such error found')
105
135
  GlobalErrorManager.register('ErrorManager', 'RIl3BUrxWOzP', 'EM_ERROR_CONVERT', 'Converted error')
106
136
  export default GlobalErrorManager
@@ -6,6 +6,7 @@
6
6
  import IPort from "../ports/IPort"
7
7
  import DeviceConnect from "./DeviceConnect"
8
8
  import Utility from "../Utility"
9
+ import Device from "./Device"
9
10
 
10
11
  /**
11
12
  * A class to implement a device port.
@@ -26,6 +27,9 @@ export default class DevicePort {
26
27
  /** Flag determines whether the port should be connected */
27
28
  required: boolean
28
29
 
30
+ /** Ссылка на устройсто владельца */
31
+ Device: Device
32
+
29
33
  /**
30
34
  * Список слушателей порта
31
35
  * Используется для захвата порта. Если какие либо данные будут проброшены
@@ -33,10 +37,11 @@ export default class DevicePort {
33
37
  */
34
38
  listens = new Map<number, (data:any) => void>()
35
39
 
36
- constructor(id: string, port: IPort) {
40
+ constructor(id: string, port: IPort, device: Device) {
37
41
  this.id = id
38
42
  this.type = port.type
39
43
  this.required = port.required
44
+ this.Device = device
40
45
  }
41
46
 
42
47
  /**
@@ -21,6 +21,16 @@ export default class BasicType {
21
21
  }
22
22
  }
23
23
 
24
+ required(){
25
+ this.rule.require = true
26
+ return this
27
+ }
28
+
29
+ /**
30
+ * Вскоре будет удален
31
+ * @see required
32
+ * @deprecated use required()
33
+ */
24
34
  require(){
25
35
  this.rule.require = true
26
36
  return this