kuzzle-device-manager 0.4.13 → 2.0.0-rc3

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.
Files changed (102) hide show
  1. package/index.d.ts +1 -0
  2. package/index.js +6 -1
  3. package/lib/DeviceManagerPlugin.d.ts +33 -65
  4. package/lib/DeviceManagerPlugin.js +142 -131
  5. package/lib/controllers/AssetController.d.ts +20 -5
  6. package/lib/controllers/AssetController.js +78 -23
  7. package/lib/controllers/DecodersController.d.ts +16 -0
  8. package/lib/controllers/DecodersController.js +27 -0
  9. package/lib/controllers/DeviceController.d.ts +25 -22
  10. package/lib/controllers/DeviceController.js +150 -109
  11. package/lib/controllers/index.d.ts +1 -1
  12. package/lib/controllers/index.js +6 -2
  13. package/lib/core-classes/AssetService.d.ts +31 -0
  14. package/lib/core-classes/AssetService.js +82 -0
  15. package/lib/core-classes/Decoder.d.ts +14 -59
  16. package/lib/core-classes/Decoder.js +16 -86
  17. package/lib/core-classes/DeviceManagerEngine.d.ts +11 -9
  18. package/lib/core-classes/DeviceManagerEngine.js +20 -32
  19. package/lib/core-classes/DeviceService.d.ts +81 -24
  20. package/lib/core-classes/DeviceService.js +178 -220
  21. package/lib/core-classes/PayloadService.d.ts +39 -26
  22. package/lib/core-classes/PayloadService.js +132 -124
  23. package/lib/core-classes/index.d.ts +5 -4
  24. package/lib/core-classes/index.js +10 -5
  25. package/lib/core-classes/{CustomMappings/AssetMappingsManager.d.ts → registers/AssetsRegister.d.ts} +8 -9
  26. package/lib/core-classes/{CustomMappings/AssetMappingsManager.js → registers/AssetsRegister.js} +17 -28
  27. package/lib/core-classes/registers/DecodersRegister.d.ts +46 -0
  28. package/lib/core-classes/registers/DecodersRegister.js +167 -0
  29. package/lib/core-classes/registers/DevicesRegister.d.ts +20 -0
  30. package/lib/core-classes/registers/DevicesRegister.js +37 -0
  31. package/lib/core-classes/registers/MeasuresRegister.d.ts +29 -0
  32. package/lib/core-classes/registers/MeasuresRegister.js +53 -0
  33. package/lib/mappings/assetsMappings.d.ts +36 -0
  34. package/lib/mappings/assetsMappings.js +36 -0
  35. package/lib/mappings/deviceMappings.d.ts +44 -0
  36. package/lib/mappings/deviceMappings.js +42 -0
  37. package/lib/mappings/index.d.ts +4 -0
  38. package/lib/mappings/index.js +21 -0
  39. package/lib/mappings/measuresMappings.d.ts +53 -0
  40. package/lib/mappings/measuresMappings.js +48 -0
  41. package/lib/mappings/payloadsMappings.d.ts +18 -0
  42. package/lib/mappings/payloadsMappings.js +16 -0
  43. package/lib/measures/BatteryMeasure.d.ts +7 -0
  44. package/lib/measures/BatteryMeasure.js +12 -0
  45. package/lib/measures/HumidityMeasure.d.ts +7 -0
  46. package/lib/measures/HumidityMeasure.js +12 -0
  47. package/lib/measures/MovementMeasure.d.ts +7 -0
  48. package/lib/measures/MovementMeasure.js +12 -0
  49. package/lib/measures/PositionMeasure.d.ts +12 -0
  50. package/lib/measures/PositionMeasure.js +16 -0
  51. package/lib/measures/TemperatureMeasure.d.ts +7 -0
  52. package/lib/measures/TemperatureMeasure.js +12 -0
  53. package/lib/measures/index.d.ts +5 -0
  54. package/lib/measures/index.js +22 -0
  55. package/lib/models/BaseAsset.d.ts +1 -48
  56. package/lib/models/BaseAsset.js +5 -43
  57. package/lib/models/Config.d.ts +1 -13
  58. package/lib/models/Device.d.ts +5 -96
  59. package/lib/models/Device.js +5 -73
  60. package/lib/models/index.d.ts +0 -1
  61. package/lib/models/index.js +5 -2
  62. package/lib/types/BaseAssetContent.d.ts +8 -3
  63. package/lib/types/DecodedPayload.d.ts +42 -0
  64. package/lib/types/{AssetsHistoryContent.js → DecodedPayload.js} +1 -1
  65. package/lib/types/DecoderContent.d.ts +4 -0
  66. package/lib/types/DecoderContent.js +3 -0
  67. package/lib/types/DeviceContent.d.ts +12 -44
  68. package/lib/types/DeviceManagerConfiguration.d.ts +40 -0
  69. package/lib/types/DeviceManagerConfiguration.js +3 -0
  70. package/lib/types/index.d.ts +7 -2
  71. package/lib/types/index.js +12 -3
  72. package/lib/types/measures/MeasureContent.d.ts +56 -0
  73. package/lib/types/measures/MeasureContent.js +3 -0
  74. package/lib/types/measures/MeasureDefinition.d.ts +40 -0
  75. package/lib/types/measures/MeasureDefinition.js +3 -0
  76. package/lib/types/measures/Measurement.d.ts +19 -0
  77. package/lib/types/{Measure.js → measures/Measurement.js} +1 -1
  78. package/lib/utils/index.d.ts +1 -1
  79. package/lib/utils/index.js +6 -2
  80. package/lib/utils/writeMany.d.ts +13 -0
  81. package/lib/utils/writeMany.js +37 -0
  82. package/package.json +14 -18
  83. package/lib/controllers/CRUDController.d.ts +0 -34
  84. package/lib/controllers/CRUDController.js +0 -65
  85. package/lib/core-classes/BatchProcessing/BatchController.d.ts +0 -34
  86. package/lib/core-classes/BatchProcessing/BatchController.js +0 -115
  87. package/lib/core-classes/BatchProcessing/BatchWriter.d.ts +0 -110
  88. package/lib/core-classes/BatchProcessing/BatchWriter.js +0 -264
  89. package/lib/core-classes/BatchProcessing/InstrumentablePromise.d.ts +0 -6
  90. package/lib/core-classes/BatchProcessing/InstrumentablePromise.js +0 -13
  91. package/lib/core-classes/BatchProcessing/index.d.ts +0 -3
  92. package/lib/core-classes/BatchProcessing/index.js +0 -16
  93. package/lib/core-classes/CustomMappings/DeviceMappingsManager.d.ts +0 -43
  94. package/lib/core-classes/CustomMappings/DeviceMappingsManager.js +0 -71
  95. package/lib/core-classes/MigrationService.d.ts +0 -13
  96. package/lib/core-classes/MigrationService.js +0 -49
  97. package/lib/models/Catalog.d.ts +0 -55
  98. package/lib/models/Catalog.js +0 -38
  99. package/lib/types/AssetsHistoryContent.d.ts +0 -9
  100. package/lib/types/Measure.d.ts +0 -54
  101. package/lib/utils/events.d.ts +0 -8
  102. package/lib/utils/events.js +0 -17
package/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './lib/DeviceManagerPlugin';
2
2
  export * from './lib/core-classes';
3
3
  export * from './lib/models';
4
+ export * from './lib/measures';
4
5
  export * from './lib/types';
package/index.js CHANGED
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -13,5 +17,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
13
17
  __exportStar(require("./lib/DeviceManagerPlugin"), exports);
14
18
  __exportStar(require("./lib/core-classes"), exports);
15
19
  __exportStar(require("./lib/models"), exports);
20
+ __exportStar(require("./lib/measures"), exports);
16
21
  __exportStar(require("./lib/types"), exports);
17
22
  //# sourceMappingURL=index.js.map
@@ -1,85 +1,54 @@
1
1
  import { Plugin, PluginContext, JSONObject } from 'kuzzle';
2
- import { Decoder, PayloadHandler, AssetMappingsManager, DeviceMappingsManager } from './core-classes';
3
- export declare type DeviceManagerConfig = {
4
- /**
5
- * Administration index name
6
- */
7
- adminIndex: string;
8
- /**
9
- * Config collection name (in admin index)
10
- */
11
- configCollection: string;
12
- /**
13
- * Administration collections mappings (in admin index)
14
- */
15
- adminCollections: {
16
- config: JSONObject;
17
- devices: JSONObject;
18
- payloads: JSONObject;
19
- };
20
- /**
21
- * Tenants collections
22
- */
23
- collections: {
24
- assets: JSONObject;
25
- devices: JSONObject;
26
- 'asset-history': JSONObject;
27
- };
28
- /**
29
- * Interval to write documents from the buffer
30
- */
31
- writerInterval: number;
32
- };
2
+ import { AssetsRegister, DevicesRegister, MeasuresRegister, DecodersRegister } from './core-classes';
3
+ import { DeviceManagerConfiguration } from './types';
33
4
  export declare class DeviceManagerPlugin extends Plugin {
34
- config: DeviceManagerConfig;
35
- private defaultConfig;
5
+ config: DeviceManagerConfiguration;
36
6
  private assetController;
37
7
  private deviceController;
8
+ private decodersController;
38
9
  private engineController;
10
+ private assetService;
39
11
  private payloadService;
40
12
  private deviceManagerEngine;
41
13
  private deviceService;
42
- private migrationService;
43
- private batchWriter;
14
+ private decodersRegister;
15
+ private measuresRegister;
16
+ private devicesRegister;
17
+ private assetsRegister;
18
+ private adminConfigManager;
19
+ private engineConfigManager;
44
20
  private get sdk();
45
21
  /**
46
- * List of registered decoders.
47
- * Map<model, decoder>
22
+ * Manager assets customization.
23
+ *
24
+ * @method register
25
+ */
26
+ get assets(): AssetsRegister;
27
+ /**
28
+ * Manage devices customization.
29
+ *
30
+ * @method registerMetadata
31
+ */
32
+ get devices(): DevicesRegister;
33
+ /**
34
+ * Manage measures customization.
35
+ *
36
+ * @method register
37
+ * @method get
48
38
  */
49
- private decoders;
50
- private deviceMappings;
51
- private assetMappings;
52
- get assets(): AssetMappingsManager;
53
- get devices(): DeviceMappingsManager;
39
+ get measures(): MeasuresRegister;
54
40
  /**
55
- * Constructor
41
+ * Manage decoders customization.
42
+ *
43
+ * @method register
44
+ * @method list
56
45
  */
46
+ get decoders(): DecodersRegister;
57
47
  constructor();
58
48
  /**
59
49
  * Init the plugin
60
50
  */
61
51
  init(config: JSONObject, context: PluginContext): Promise<void>;
62
- /**
63
- * Registers a new decoder for a device model.
64
- *
65
- * This will register a new API action:
66
- * - controller: `"device-manager/payload"`
67
- * - action: `action` property of the decoder or the device model in kebab-case
68
- *
69
- * If a custom payload handler is given then it will be used to process payloads
70
- * instead of the PayloadService.process method.
71
- *
72
- * @param decoder Instantiated decoder
73
- * @param options.handler Custom payload handler
74
- *
75
- * @returns Corresponding API action requestPayload
76
- */
77
- registerDecoder(decoder: Decoder, { handler }?: {
78
- handler?: PayloadHandler;
79
- }): {
80
- controller: string;
81
- action: string;
82
- };
83
52
  /**
84
53
  * Initialize the administration index of the plugin
85
54
  */
@@ -96,5 +65,4 @@ export declare class DeviceManagerPlugin extends Plugin {
96
65
  */
97
66
  private initializeConfig;
98
67
  private pipeCheckEngine;
99
- private generateConfigID;
100
68
  }
@@ -9,139 +9,157 @@ const kuzzle_1 = require("kuzzle");
9
9
  const kuzzle_plugin_commons_1 = require("kuzzle-plugin-commons");
10
10
  const controllers_1 = require("./controllers");
11
11
  const core_classes_1 = require("./core-classes");
12
- const models_1 = require("./models");
12
+ const measures_1 = require("./measures");
13
+ const mappings_1 = require("./mappings");
13
14
  class DeviceManagerPlugin extends kuzzle_1.Plugin {
14
- /**
15
- * Constructor
16
- */
17
15
  constructor() {
18
16
  super({
19
- kuzzleVersion: '>=2.14.0 <3'
17
+ kuzzleVersion: '>=2.16.8 <3'
20
18
  });
21
- /**
22
- * List of registered decoders.
23
- * Map<model, decoder>
24
- */
25
- this.decoders = new Map();
26
- this.deviceMappings = new core_classes_1.DeviceMappingsManager(models_1.devicesMappings);
27
- this.assetMappings = new core_classes_1.AssetMappingsManager(models_1.assetsMappings, this.deviceMappings);
19
+ this.decodersRegister = new core_classes_1.DecodersRegister();
20
+ this.measuresRegister = new core_classes_1.MeasuresRegister();
21
+ this.devicesRegister = new core_classes_1.DevicesRegister(this.measuresRegister);
22
+ this.assetsRegister = new core_classes_1.AssetsRegister(this.measuresRegister);
28
23
  this.api = {
29
24
  'device-manager/payload': {
30
25
  actions: {}
31
26
  }
32
27
  };
33
- this.defaultConfig = {
28
+ /* eslint-disable sort-keys */
29
+ this.config = {
34
30
  adminIndex: 'device-manager',
35
- configCollection: 'config',
36
31
  adminCollections: {
37
32
  config: {
38
- dynamic: 'strict',
39
- properties: {
40
- type: { type: 'keyword' },
41
- engine: {
42
- properties: {
43
- index: { type: 'keyword' },
44
- group: { type: 'keyword' },
45
- }
46
- },
47
- catalog: models_1.catalogMappings,
48
- 'device-manager': {
49
- properties: {
50
- autoProvisionning: { type: 'boolean' },
51
- }
52
- }
53
- }
33
+ name: 'config',
34
+ mappings: {
35
+ dynamic: 'strict',
36
+ properties: {}
37
+ },
38
+ settings: {},
39
+ },
40
+ devices: {
41
+ name: 'devices',
42
+ mappings: mappings_1.devicesMappings,
43
+ settings: {},
54
44
  },
55
- devices: models_1.devicesMappings,
56
45
  payloads: {
57
- dynamic: 'strict',
58
- properties: {
59
- uuid: { type: 'keyword' },
60
- valid: { type: 'boolean' },
61
- deviceModel: { type: 'keyword' },
62
- payload: {
63
- dynamic: 'false',
64
- properties: {}
65
- }
66
- }
46
+ name: 'payloads',
47
+ mappings: mappings_1.payloadsMappings,
48
+ settings: {},
67
49
  }
68
50
  },
69
- collections: {
70
- assets: models_1.assetsMappings,
71
- devices: models_1.devicesMappings,
72
- 'asset-history': models_1.assetsHistoryMappings,
51
+ engineCollections: {
52
+ config: {
53
+ name: 'config',
54
+ mappings: {
55
+ dynamic: 'strict',
56
+ properties: {}
57
+ },
58
+ settings: {}
59
+ }
73
60
  },
74
- writerInterval: 50
61
+ batchInterval: 10
75
62
  };
63
+ /* eslint-enable sort-keys */
76
64
  }
77
65
  get sdk() {
78
66
  return this.context.accessors.sdk;
79
67
  }
68
+ /**
69
+ * Manager assets customization.
70
+ *
71
+ * @method register
72
+ */
80
73
  get assets() {
81
- return this.assetMappings;
74
+ return this.assetsRegister;
82
75
  }
76
+ /**
77
+ * Manage devices customization.
78
+ *
79
+ * @method registerMetadata
80
+ */
83
81
  get devices() {
84
- return this.deviceMappings;
82
+ return this.devicesRegister;
83
+ }
84
+ /**
85
+ * Manage measures customization.
86
+ *
87
+ * @method register
88
+ * @method get
89
+ */
90
+ get measures() {
91
+ return this.measuresRegister;
92
+ }
93
+ /**
94
+ * Manage decoders customization.
95
+ *
96
+ * @method register
97
+ * @method list
98
+ */
99
+ get decoders() {
100
+ return this.decodersRegister;
85
101
  }
86
102
  /**
87
103
  * Init the plugin
88
104
  */
89
105
  async init(config, context) {
90
- this.config = lodash_1.default.merge({}, this.defaultConfig, config);
106
+ this.config = lodash_1.default.merge({}, this.config, config);
91
107
  this.context = context;
92
- this.batchWriter = new core_classes_1.BatchWriter(this.sdk, { interval: this.config.writerInterval });
93
- this.batchWriter.begin();
94
- this.payloadService = new core_classes_1.PayloadService(this, this.batchWriter);
95
- this.deviceService = new core_classes_1.DeviceService(this, this.decoders);
96
- this.migrationService = new core_classes_1.MigrationService('device-manager', this);
97
- this.deviceManagerEngine = new core_classes_1.DeviceManagerEngine(this, this.assetMappings, this.deviceMappings);
98
- this.assetController = new controllers_1.AssetController(this);
108
+ /* eslint-disable sort-keys */
109
+ this.pipes = {
110
+ 'device-manager/asset:before*': this.pipeCheckEngine.bind(this),
111
+ 'device-manager/device:beforeAttachEngine': this.pipeCheckEngine.bind(this),
112
+ 'device-manager/device:beforeSearch': this.pipeCheckEngine.bind(this),
113
+ 'device-manager/device:beforeUpdate': this.pipeCheckEngine.bind(this),
114
+ 'generic:document:beforeWrite': [],
115
+ };
116
+ /* eslint-enable sort-keys */
117
+ this.adminConfigManager = new kuzzle_plugin_commons_1.ConfigManager(this, {
118
+ mappings: this.config.adminCollections.config.mappings,
119
+ settings: this.config.adminCollections.config.settings,
120
+ });
121
+ this.adminConfigManager.register('device-manager', {
122
+ properties: {
123
+ provisioningStrategy: { type: 'keyword' },
124
+ }
125
+ });
126
+ this.adminConfigManager.register('engine', {
127
+ properties: {
128
+ group: { type: 'keyword' },
129
+ index: { type: 'keyword' },
130
+ name: { type: 'keyword' },
131
+ }
132
+ });
133
+ this.engineConfigManager = new kuzzle_plugin_commons_1.ConfigManager(this, {
134
+ mappings: this.config.engineCollections.config.mappings,
135
+ settings: this.config.engineCollections.config.settings,
136
+ });
137
+ this.measures.register('temperature', measures_1.temperatureMeasure);
138
+ this.measures.register('position', measures_1.positionMeasure);
139
+ this.measures.register('movement', measures_1.movementMeasure);
140
+ this.measures.register('humidity', measures_1.humidityMeasure);
141
+ this.measures.register('battery', measures_1.batteryMeasure);
142
+ this.assetService = new core_classes_1.AssetService(this);
143
+ this.payloadService = new core_classes_1.PayloadService(this, this.measuresRegister);
144
+ this.deviceService = new core_classes_1.DeviceService(this);
145
+ this.deviceManagerEngine = new core_classes_1.DeviceManagerEngine(this, this.assetsRegister, this.devicesRegister, this.measuresRegister, this.adminConfigManager, this.engineConfigManager);
146
+ this.decodersRegister.init(this.context);
147
+ this.assetController = new controllers_1.AssetController(this, this.assetService);
99
148
  this.deviceController = new controllers_1.DeviceController(this, this.deviceService);
149
+ this.decodersController = new controllers_1.DecodersController(this, this.decodersRegister);
100
150
  this.engineController = new kuzzle_plugin_commons_1.EngineController('device-manager', this, this.deviceManagerEngine);
151
+ this.api['device-manager/payload'] = this.decodersRegister.getPayloadController(this.payloadService);
101
152
  this.api['device-manager/asset'] = this.assetController.definition;
102
153
  this.api['device-manager/device'] = this.deviceController.definition;
103
- this.pipes = {
104
- 'device-manager/device:beforeUpdate': this.pipeCheckEngine.bind(this),
105
- 'device-manager/device:beforeSearch': this.pipeCheckEngine.bind(this),
106
- 'device-manager/device:beforeAttachTenant': this.pipeCheckEngine.bind(this),
107
- 'device-manager/asset:before*': this.pipeCheckEngine.bind(this),
108
- 'document:beforeCreate': this.generateConfigID.bind(this),
154
+ this.api['device-manager/decoders'] = this.decodersController.definition;
155
+ this.hooks = {
156
+ 'kuzzle:state:live': async () => {
157
+ await this.decodersRegister.createDefaultRights();
158
+ this.context.log.info('Default rights for payload controller has been registered.');
159
+ }
109
160
  };
161
+ this.decodersRegister.printDecoders();
110
162
  await this.initDatabase();
111
- await this.migrationService.run();
112
- for (const decoder of this.decoders.values()) {
113
- this.context.log.info(`Register API action "device-manager/payload:${decoder.action}" with decoder "${decoder.constructor.name}" for device "${decoder.deviceModel}"`);
114
- }
115
- }
116
- /**
117
- * Registers a new decoder for a device model.
118
- *
119
- * This will register a new API action:
120
- * - controller: `"device-manager/payload"`
121
- * - action: `action` property of the decoder or the device model in kebab-case
122
- *
123
- * If a custom payload handler is given then it will be used to process payloads
124
- * instead of the PayloadService.process method.
125
- *
126
- * @param decoder Instantiated decoder
127
- * @param options.handler Custom payload handler
128
- *
129
- * @returns Corresponding API action requestPayload
130
- */
131
- registerDecoder(decoder, { handler } = {}) {
132
- decoder.action = decoder.action || kuzzle_1.Inflector.kebabCase(decoder.deviceModel);
133
- if (this.api['device-manager/payload'].actions[decoder.action]) {
134
- throw new kuzzle_1.PluginImplementationError(`A decoder for "${decoder.deviceModel}" has already been registered.`);
135
- }
136
- this.api['device-manager/payload'].actions[decoder.action] = {
137
- handler: request => handler ? handler(request, decoder) : this.payloadService.process(request, decoder),
138
- http: decoder.http,
139
- };
140
- this.decoders.set(decoder.deviceModel, decoder);
141
- return {
142
- controller: 'device-manager/payload',
143
- action: decoder.action,
144
- };
145
163
  }
146
164
  /**
147
165
  * Initialize the administration index of the plugin
@@ -164,19 +182,21 @@ class DeviceManagerPlugin extends kuzzle_1.Plugin {
164
182
  }
165
183
  }
166
184
  await Promise.all([
167
- this.sdk.collection.create(this.config.adminIndex, this.config.configCollection, this.config.adminCollections.config),
168
- this.sdk.collection.create(this.config.adminIndex, 'devices', this.deviceMappings.get()),
169
- this.sdk.collection.create(this.config.adminIndex, 'payloads', this.getPayloadsMappings()),
185
+ this.adminConfigManager.createCollection(this.config.adminIndex)
186
+ .catch(error => {
187
+ throw new kuzzle_1.PluginImplementationError(`Cannot create admin "config" collection: ${error}`);
188
+ }),
189
+ this.sdk.collection.create(this.config.adminIndex, 'devices', this.devicesRegister.getMappings())
190
+ .catch(error => {
191
+ throw new kuzzle_1.PluginImplementationError(`Cannot create admin "devices" collection: ${error}`);
192
+ }),
193
+ this.sdk.collection.create(this.config.adminIndex, 'payloads', this.getPayloadsMappings())
194
+ .catch(error => {
195
+ throw new kuzzle_1.PluginImplementationError(`Cannot create admin "payloads" collection: ${error}`);
196
+ }),
170
197
  ]);
171
198
  await this.initializeConfig();
172
199
  }
173
- catch (error) {
174
- // When nodes are starting at the same time, the index cache synchronization
175
- // message is received too late so index.exists returns false
176
- if (error.id !== 'services.storage.index_already_exists') {
177
- throw error;
178
- }
179
- }
180
200
  finally {
181
201
  await mutex.unlock();
182
202
  }
@@ -188,8 +208,8 @@ class DeviceManagerPlugin extends kuzzle_1.Plugin {
188
208
  * Those custom mappings allow to search raw payloads more efficiently.
189
209
  */
190
210
  getPayloadsMappings() {
191
- const mappings = JSON.parse(JSON.stringify(this.config.adminCollections.payloads));
192
- for (const decoder of this.decoders.values()) {
211
+ const { mappings } = JSON.parse(JSON.stringify(this.config.adminCollections.payloads));
212
+ for (const decoder of this.decodersRegister.decoders) {
193
213
  mappings.properties.payload.properties = {
194
214
  ...mappings.properties.payload.properties,
195
215
  ...decoder.payloadsMappings
@@ -201,35 +221,26 @@ class DeviceManagerPlugin extends kuzzle_1.Plugin {
201
221
  * Initialize the config document if it does not exists
202
222
  */
203
223
  async initializeConfig() {
204
- const exists = await this.sdk.document.exists(this.config.adminIndex, this.config.configCollection, 'plugin--device-manager');
224
+ const exists = await this.sdk.document.exists(this.config.adminIndex, this.adminConfigManager.collection, 'plugin--device-manager');
205
225
  if (!exists) {
206
- await this.sdk.document.create(this.config.adminIndex, this.config.configCollection, {
207
- type: 'device-manager',
208
- 'device-manager': { autoProvisionning: true }
226
+ await this.sdk.document.create(this.config.adminIndex, this.adminConfigManager.collection, {
227
+ 'device-manager': { provisioningStrategy: 'auto' },
228
+ type: 'device-manager'
209
229
  }, 'plugin--device-manager');
210
230
  }
211
231
  }
212
232
  async pipeCheckEngine(request) {
213
- const index = request.getIndex();
214
- const { result: { exists } } = await this.sdk.query({
215
- controller: 'device-manager/engine',
216
- action: 'exists',
217
- index,
218
- });
219
- if (!exists) {
220
- throw new kuzzle_1.BadRequestError(`Tenant "${index}" does not have a device-manager engine`);
221
- }
222
- return request;
223
- }
224
- async generateConfigID(request) {
225
- if (request.getCollection() !== this.config.configCollection) {
226
- return request;
227
- }
228
- const document = request.getBody();
229
- if (document.type !== 'catalog' || request.getId(({ ifMissing: 'ignore' }))) {
230
- return request;
233
+ const engineId = request.getString('engineId');
234
+ if (engineId !== this.config.adminIndex) {
235
+ const { result: { exists } } = await this.sdk.query({
236
+ action: 'exists',
237
+ controller: 'device-manager/engine',
238
+ index: engineId,
239
+ });
240
+ if (!exists) {
241
+ throw new kuzzle_1.BadRequestError(`Tenant "${engineId}" does not have a device-manager engine`);
242
+ }
231
243
  }
232
- request.input.args._id = `catalog--${document.catalog.deviceId}`;
233
244
  return request;
234
245
  }
235
246
  }
@@ -1,7 +1,22 @@
1
- import { KuzzleRequest, EmbeddedSDK, Plugin } from 'kuzzle';
2
- import { CRUDController } from './CRUDController';
1
+ import { CRUDController } from 'kuzzle-plugin-commons';
2
+ import { KuzzleRequest, Plugin } from 'kuzzle';
3
+ import { AssetService } from '../core-classes';
3
4
  export declare class AssetController extends CRUDController {
4
- get sdk(): EmbeddedSDK;
5
- constructor(plugin: Plugin);
6
- create(request: KuzzleRequest): Promise<import("kuzzle").Document>;
5
+ private assetService;
6
+ private get sdk();
7
+ constructor(plugin: Plugin, assetService: AssetService);
8
+ measures(request: KuzzleRequest): Promise<{
9
+ measures: import("kuzzle").KDocument<import("../types").MeasureContent>[];
10
+ }>;
11
+ update(request: KuzzleRequest): Promise<import("kuzzle").KDocument<{
12
+ [x: string]: any;
13
+ }>>;
14
+ create(request: KuzzleRequest): Promise<import("kuzzle").KDocument<{
15
+ [x: string]: any;
16
+ }>>;
17
+ importAssets(request: KuzzleRequest): Promise<{
18
+ errors: any[];
19
+ successes: any[];
20
+ }>;
21
+ delete(request: KuzzleRequest): Promise<string>;
7
22
  }
@@ -1,52 +1,107 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.AssetController = void 0;
4
- const CRUDController_1 = require("./CRUDController");
7
+ const csvtojson_1 = __importDefault(require("csvtojson"));
8
+ const kuzzle_plugin_commons_1 = require("kuzzle-plugin-commons");
9
+ const kuzzle_1 = require("kuzzle");
5
10
  const BaseAsset_1 = require("../models/BaseAsset");
6
- class AssetController extends CRUDController_1.CRUDController {
7
- get sdk() {
8
- return this.context.accessors.sdk;
9
- }
10
- constructor(plugin) {
11
+ class AssetController extends kuzzle_plugin_commons_1.CRUDController {
12
+ constructor(plugin, assetService) {
11
13
  super(plugin, 'assets');
14
+ this.assetService = assetService;
15
+ /* eslint-disable sort-keys */
12
16
  this.definition = {
13
17
  actions: {
14
18
  create: {
15
19
  handler: this.create.bind(this),
16
- http: [{ verb: 'post', path: 'device-manager/:index/assets' }],
17
- },
18
- update: {
19
- handler: this.update.bind(this),
20
- http: [{ verb: 'put', path: 'device-manager/:index/assets/:_id' }],
20
+ http: [{ path: 'device-manager/:index/assets', verb: 'post' }],
21
21
  },
22
22
  delete: {
23
23
  handler: this.delete.bind(this),
24
- http: [{ verb: 'delete', path: 'device-manager/:index/assets/:_id' }],
24
+ http: [{ path: 'device-manager/:index/assets/:_id', verb: 'delete' }],
25
+ },
26
+ importAssets: {
27
+ handler: this.importAssets.bind(this),
28
+ http: [{ path: 'device-manager/:index/assets/_import', verb: 'post' }]
25
29
  },
26
30
  search: {
27
31
  handler: this.search.bind(this),
28
32
  http: [
29
- { verb: 'post', path: 'device-manager/:index/assets/_search' },
30
- { verb: 'get', path: 'device-manager/:index/assets/_search' },
33
+ { path: 'device-manager/:index/assets/_search', verb: 'post' },
34
+ { path: 'device-manager/:index/assets/_search', verb: 'get' },
31
35
  ],
32
36
  },
37
+ update: {
38
+ handler: this.update.bind(this),
39
+ http: [{ path: 'device-manager/:index/assets/:_id', verb: 'put' }],
40
+ },
41
+ measures: {
42
+ handler: this.measures.bind(this),
43
+ http: [{ path: 'device-manager/:index/assets/:_id/measures', verb: 'get' }],
44
+ }
33
45
  },
34
46
  };
47
+ /* eslint-enable sort-keys */
48
+ }
49
+ get sdk() {
50
+ return this.context.accessors.sdk;
51
+ }
52
+ async measures(request) {
53
+ const id = request.getId();
54
+ const engineId = request.getString('engineId');
55
+ const size = request.input.args.size;
56
+ const startAt = request.input.args.startAt;
57
+ const endAt = request.input.args.endAt;
58
+ if (size && startAt || size && endAt) {
59
+ throw new kuzzle_1.BadRequestError('You cannot specify both a "size" and a "startAt" or "endAt"');
60
+ }
61
+ const measures = await this.assetService.measureHistory(engineId, id, { endAt, size, startAt });
62
+ return { measures };
63
+ }
64
+ async update(request) {
65
+ const id = request.getId();
66
+ const engineId = request.getString('engineId');
67
+ const body = request.getBody();
68
+ const asset = await this.sdk.document.get(engineId, this.collection, id);
69
+ const response = await global.app.trigger('device-manager:asset:update:before', {
70
+ asset,
71
+ updates: body
72
+ });
73
+ request.input.args.index = engineId;
74
+ request.input.body = response.updates;
75
+ const result = await super.update(request);
76
+ await global.app.trigger('device-manager:asset:update:after', {
77
+ asset,
78
+ updates: result._source,
79
+ });
80
+ return result;
35
81
  }
36
82
  async create(request) {
37
83
  const type = request.getBodyString('type');
38
84
  const model = request.getBodyString('model');
39
85
  const reference = request.getBodyString('reference');
40
- if (!request.input.resource._id) {
41
- const assetContent = {
42
- type,
43
- model,
44
- reference,
45
- };
46
- const asset = new BaseAsset_1.BaseAsset(assetContent);
47
- request.input.resource._id = asset._id;
86
+ if (!request.input.args._id) {
87
+ request.input.args._id = BaseAsset_1.BaseAsset.id(type, model, reference);
48
88
  }
49
- return await super.create(request);
89
+ request.input.args.index = request.getString('engineId');
90
+ return super.create(request);
91
+ }
92
+ async importAssets(request) {
93
+ const engineId = request.getString('engineId');
94
+ const content = request.getBodyString('csv');
95
+ const assets = await (0, csvtojson_1.default)({ delimiter: 'auto' }).fromString(content);
96
+ const results = await this.assetService.importAssets(engineId, assets, {
97
+ options: { ...request.input.args },
98
+ strict: true
99
+ });
100
+ return results;
101
+ }
102
+ async delete(request) {
103
+ request.input.args.index = request.getString('engineId');
104
+ return super.delete(request);
50
105
  }
51
106
  }
52
107
  exports.AssetController = AssetController;