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
@@ -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];
@@ -10,7 +14,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
15
  };
12
16
  Object.defineProperty(exports, "__esModule", { value: true });
13
- __exportStar(require("./Measure"), exports);
14
- __exportStar(require("./DeviceContent"), exports);
15
17
  __exportStar(require("./BaseAssetContent"), exports);
18
+ __exportStar(require("./DeviceContent"), exports);
19
+ __exportStar(require("./measures/MeasureContent"), exports);
20
+ __exportStar(require("./measures/Measurement"), exports);
21
+ __exportStar(require("./measures/MeasureDefinition"), exports);
22
+ __exportStar(require("./DecoderContent"), exports);
23
+ __exportStar(require("./DecodedPayload"), exports);
24
+ __exportStar(require("./DeviceManagerConfiguration"), exports);
16
25
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,56 @@
1
+ import { JSONObject } from 'kuzzle';
2
+ import { KDocumentContent } from 'kuzzle-sdk';
3
+ import { MeasurementUnit } from './MeasureDefinition';
4
+ /**
5
+ * Represent the content of a measure document.
6
+ */
7
+ export interface MeasureContent extends KDocumentContent {
8
+ /**
9
+ * Type of the measure. (e.g. "temperature")
10
+ * The type name is also the name of the sub-property to look at
11
+ * in the "values" object to get the measure main value.
12
+ */
13
+ type: string;
14
+ /**
15
+ * A device may have different measures for the same type (e.g. measure temperature 2 times)
16
+ * Should be set when you link the device to the asset
17
+ */
18
+ name?: string;
19
+ /**
20
+ * Measurement self-description
21
+ */
22
+ unit: MeasurementUnit;
23
+ /**
24
+ * Mesured values
25
+ */
26
+ values: JSONObject;
27
+ /**
28
+ * Micro Timestamp of the measure
29
+ */
30
+ measuredAt: number;
31
+ /**
32
+ * Origin of the measure
33
+ */
34
+ origin: {
35
+ /**
36
+ * ID of the device (document _id)
37
+ */
38
+ id: string;
39
+ /**
40
+ * E.g. "device"
41
+ */
42
+ type: string;
43
+ /**
44
+ * E.g. "AbeewayTemp"
45
+ */
46
+ model: string;
47
+ /**
48
+ * Array of payload uuids that were used to create this measure.
49
+ */
50
+ payloadUuids: string[];
51
+ /**
52
+ * Asset ID linked to the device when the measure was made
53
+ */
54
+ assetId?: string;
55
+ };
56
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=MeasureContent.js.map
@@ -0,0 +1,40 @@
1
+ import { JSONObject } from 'kuzzle';
2
+ /**
3
+ * Represents a measurement unit definition
4
+ *
5
+ * @example
6
+ * {
7
+ name: 'Degree',
8
+ sign: '°',
9
+ type: 'number',
10
+ }
11
+ *
12
+ */
13
+ export interface MeasurementUnit {
14
+ name: string;
15
+ sign: string;
16
+ type: string;
17
+ }
18
+ /**
19
+ * Represents a measure definition registered by the Device Manager
20
+ *
21
+ * @example
22
+ * {
23
+ * measurementMappings: { temperature: { type: 'float' } },
24
+ unit: {
25
+ name: 'Degree',
26
+ sign: '°',
27
+ type: 'number',
28
+ },
29
+ }
30
+ */
31
+ export interface MeasureDefinition {
32
+ /**
33
+ * Unit definition
34
+ */
35
+ unit: MeasurementUnit;
36
+ /**
37
+ * Mappings for the measurement values in order to index the fields
38
+ */
39
+ valuesMappings: JSONObject;
40
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=MeasureDefinition.js.map
@@ -0,0 +1,19 @@
1
+ import { JSONObject } from 'kuzzle';
2
+ /**
3
+ * Represents a measurement of a value
4
+ *
5
+ * This interface should be extended and the `values` property specialized
6
+ * to declare new measurement type.
7
+ */
8
+ export interface Measurement {
9
+ /**
10
+ * Property containing the actual measurement.
11
+ *
12
+ * This should be specialized by child interfaces
13
+ */
14
+ values: JSONObject;
15
+ /**
16
+ * Micro Timestamp of the measurement time
17
+ */
18
+ measuredAt: number;
19
+ }
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=Measure.js.map
3
+ //# sourceMappingURL=Measurement.js.map
@@ -1 +1 @@
1
- export * from './events';
1
+ export * from './writeMany';
@@ -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];
@@ -10,5 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
15
  };
12
16
  Object.defineProperty(exports, "__esModule", { value: true });
13
- __exportStar(require("./events"), exports);
17
+ __exportStar(require("./writeMany"), exports);
14
18
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,13 @@
1
+ import { JSONObject } from 'kuzzle';
2
+ export declare type mRequest = {
3
+ _id: string;
4
+ body: JSONObject;
5
+ };
6
+ export declare type mResponse = {
7
+ successes: JSONObject[];
8
+ errors: JSONObject[];
9
+ };
10
+ export declare function writeToDatabase(documents: mRequest[], writer: (docs: mRequest[]) => Promise<mResponse>): Promise<{
11
+ errors: any[];
12
+ successes: any[];
13
+ }>;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.writeToDatabase = void 0;
4
+ async function writeToDatabase(documents, writer) {
5
+ const results = {
6
+ errors: [],
7
+ successes: [],
8
+ };
9
+ const limit = global.kuzzle.config.limits.documentsWriteCount;
10
+ if (documents.length <= limit) {
11
+ const { successes, errors } = await writer(documents);
12
+ results.successes.concat(successes);
13
+ results.errors.concat(errors);
14
+ return results;
15
+ }
16
+ const writeMany = async (start, end) => {
17
+ const devices = documents.slice(start, end);
18
+ const { successes, errors } = await writer(devices);
19
+ results.successes.concat(successes);
20
+ results.errors.concat(errors);
21
+ };
22
+ let offset = 0;
23
+ let offsetLimit = limit;
24
+ let done = false;
25
+ while (!done) {
26
+ await writeMany(offset, offsetLimit);
27
+ offset += limit;
28
+ offsetLimit += limit;
29
+ if (offsetLimit >= documents.length) {
30
+ done = true;
31
+ await writeMany(offset, documents.length);
32
+ }
33
+ }
34
+ return results;
35
+ }
36
+ exports.writeToDatabase = writeToDatabase;
37
+ //# sourceMappingURL=writeMany.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "kuzzle-device-manager",
3
- "version": "0.4.13",
4
- "description": "Manage your IoT devices and assets. Choose a provisionning strategy, receive and decode payload, handle your IoT business logic.",
3
+ "version": "2.0.0-rc3",
4
+ "description": "Manage your IoT devices and assets. Choose a provisioning strategy, receive and decode payload, handle your IoT business logic.",
5
5
  "author": "The Kuzzle Team (support@kuzzle.io)",
6
6
  "repository": {
7
7
  "type": "git",
@@ -25,32 +25,28 @@
25
25
  "license": "Apache-2.0",
26
26
  "dependencies": {
27
27
  "csvtojson": "~2.0.10",
28
- "kuzzle-plugin-commons": "https://github.com/kuzzleio/kuzzle-plugin-commons/archive/refs/tags/0.0.1.tar.gz",
28
+ "json-stable-stringify": "^1.0.1",
29
+ "kuzzle-plugin-commons": "https://github.com/kuzzleio/kuzzle-plugin-commons/archive/refs/tags/1.0.4.tar.gz",
29
30
  "uuid": "~8.3.2"
30
31
  },
31
32
  "devDependencies": {
32
- "@types/node": "^16.11.11",
33
- "@typescript-eslint/eslint-plugin": "^5.5.0",
34
- "@typescript-eslint/parser": "^5.5.0",
33
+ "@types/node": "^17.0.21",
34
+ "@typescript-eslint/eslint-plugin": "^5.14.0",
35
+ "@typescript-eslint/parser": "^5.14.0",
35
36
  "cucumber": "^6.0.5",
36
- "ergol": "^1.0.1",
37
- "eslint": "^8.4.0",
37
+ "ergol": "^1.0.2",
38
+ "eslint": "^8.10.0",
38
39
  "eslint-friendly-formatter": "^4.0.1",
39
40
  "eslint-loader": "^4.0.2",
40
- "kuzzle": "^2.15.2",
41
- "kuzzle-sdk": "^7.7.6",
41
+ "kuzzle": "^2.17.6",
42
+ "kuzzle-sdk": "^7.9.1",
42
43
  "lodash": "^4.17.21",
43
- "mocha": "^9.1.3",
44
- "mock-require": "^3.0.3",
45
- "rewire": "^5.0.0",
46
44
  "should": "^13.2.3",
47
- "should-sinon": "^0.0.6",
48
- "sinon": "^12.0.1",
49
- "ts-node": "^10.4.0",
50
- "typescript": "^4.5.2"
45
+ "ts-node": "^10.7.0",
46
+ "typescript": "^4.6.2"
51
47
  },
52
48
  "peerDependencies": {
53
- "kuzzle": "^2.15.2"
49
+ "kuzzle": "^2.17.3"
54
50
  },
55
51
  "files": [
56
52
  "index.js",
@@ -1,34 +0,0 @@
1
- import { KuzzleRequest, PluginContext, ControllerDefinition, Plugin } from 'kuzzle';
2
- import { DeviceManagerConfig } from '../DeviceManagerPlugin';
3
- export declare class CRUDController {
4
- protected context: PluginContext;
5
- protected config: DeviceManagerConfig;
6
- private collection;
7
- definition: ControllerDefinition;
8
- constructor(plugin: Plugin, collection: string);
9
- get as(): (user: any) => import("kuzzle").EmbeddedSDK;
10
- /**
11
- * Create an asset or a device depending on the collection.
12
- *
13
- * @param request
14
- */
15
- create(request: KuzzleRequest): Promise<import("kuzzle").Document>;
16
- /**
17
- * Delete an asset or a device depending on the collection.
18
- *
19
- * @param request
20
- */
21
- delete(request: KuzzleRequest): Promise<number>;
22
- /**
23
- * search assets or devices depending on the collection.
24
- *
25
- * @param request
26
- */
27
- search(request: KuzzleRequest): Promise<any>;
28
- /**
29
- * Create an asset or a device depending on the collection.
30
- *
31
- * @param request
32
- */
33
- update(request: KuzzleRequest): Promise<import("kuzzle").Document>;
34
- }
@@ -1,65 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CRUDController = void 0;
4
- class CRUDController {
5
- constructor(plugin, collection) {
6
- this.config = plugin.config;
7
- this.context = plugin.context;
8
- this.collection = collection;
9
- }
10
- get as() {
11
- return user => this.context.accessors.sdk.as(user, { checkRights: true });
12
- }
13
- /**
14
- * Create an asset or a device depending on the collection.
15
- *
16
- * @param request
17
- */
18
- async create(request) {
19
- const index = request.getIndex();
20
- const asset = request.getBody();
21
- const id = request.input.resource._id;
22
- return this.as(request.context.user).document.create(index, this.collection, asset, id, { ...request.input.args });
23
- }
24
- /**
25
- * Delete an asset or a device depending on the collection.
26
- *
27
- * @param request
28
- */
29
- async delete(request) {
30
- const index = request.getIndex();
31
- const id = request.getId();
32
- return this.as(request.context.user).document.delete(index, this.collection, id, { ...request.input.args });
33
- }
34
- /**
35
- * search assets or devices depending on the collection.
36
- *
37
- * @param request
38
- */
39
- async search(request) {
40
- const index = request.getIndex();
41
- const { searchBody } = request.getSearchParams();
42
- const res = await this.as(request.context.user).query({
43
- controller: 'document',
44
- action: 'search',
45
- index,
46
- collection: this.collection,
47
- body: searchBody,
48
- ...request.input.args
49
- });
50
- return res.result;
51
- }
52
- /**
53
- * Create an asset or a device depending on the collection.
54
- *
55
- * @param request
56
- */
57
- async update(request) {
58
- const index = request.getIndex();
59
- const body = request.getBody();
60
- const id = request.getId();
61
- return this.as(request.context.user).document.update(index, this.collection, id, body, { ...request.input.args });
62
- }
63
- }
64
- exports.CRUDController = CRUDController;
65
- //# sourceMappingURL=CRUDController.js.map
@@ -1,34 +0,0 @@
1
- import { DocumentController, Kuzzle as KuzzleSDK, JSONObject } from 'kuzzle';
2
- import { BatchWriter } from './BatchWriter';
3
- /**
4
- * Overload of the document controller.
5
- *
6
- * This class replace the following methods and will execute them by batch using
7
- * m* actions:
8
- * - create
9
- * - replace
10
- * - createOrReplace
11
- * - update
12
- * - get
13
- * - exists
14
- * - delete
15
- *
16
- * The m* actions returns the successes in the same order as in the request so
17
- * since we have the index of the single document inside the array of documents
18
- * sent to the action, we can retrieve the corresponding result in the array of
19
- * results.
20
- *
21
- */
22
- export declare class BatchController extends DocumentController {
23
- writer: BatchWriter;
24
- constructor(sdk: KuzzleSDK, writer: BatchWriter);
25
- protected extractErrorById(id: string, errors: any[]): any;
26
- protected extractErrorByContent(content: JSONObject, errors: any[]): any;
27
- create(index: string, collection: string, content: JSONObject, _id?: string, options?: JSONObject): Promise<any>;
28
- replace(index: string, collection: string, _id: string, content: JSONObject, options?: JSONObject): Promise<any>;
29
- createOrReplace(index: string, collection: string, _id: string, content: JSONObject, options?: JSONObject): Promise<any>;
30
- update(index: string, collection: string, _id: string, changes: JSONObject, options?: JSONObject): Promise<any>;
31
- get(index: string, collection: string, id: string): Promise<any>;
32
- exists(index: string, collection: string, id: string): Promise<any>;
33
- delete(index: string, collection: string, id: string): Promise<any>;
34
- }
@@ -1,115 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.BatchController = void 0;
7
- const lodash_1 = __importDefault(require("lodash"));
8
- const json_stable_stringify_1 = __importDefault(require("json-stable-stringify"));
9
- const kuzzle_1 = require("kuzzle");
10
- /**
11
- * Overload of the document controller.
12
- *
13
- * This class replace the following methods and will execute them by batch using
14
- * m* actions:
15
- * - create
16
- * - replace
17
- * - createOrReplace
18
- * - update
19
- * - get
20
- * - exists
21
- * - delete
22
- *
23
- * The m* actions returns the successes in the same order as in the request so
24
- * since we have the index of the single document inside the array of documents
25
- * sent to the action, we can retrieve the corresponding result in the array of
26
- * results.
27
- *
28
- */
29
- class BatchController extends kuzzle_1.DocumentController {
30
- constructor(sdk, writer) {
31
- super(sdk);
32
- this.writer = writer;
33
- }
34
- extractErrorById(id, errors) {
35
- return errors.find(({ document }) => document._id === id);
36
- }
37
- extractErrorByContent(content, errors) {
38
- return errors.find(e => {
39
- const responseDoc = (0, json_stable_stringify_1.default)(lodash_1.default.omit(e.document._source, ['_kuzzle_info']));
40
- const originDoc = (0, json_stable_stringify_1.default)(content);
41
- return responseDoc === originDoc;
42
- });
43
- }
44
- async create(index, collection, content, _id, options) {
45
- try {
46
- const { idx, promise } = this.writer.addCreate(index, collection, content, _id, options);
47
- const { successes, errors } = await promise.promise;
48
- if (errors.length > 0) {
49
- const error = this.extractErrorByContent(content, errors);
50
- if (error) {
51
- throw new kuzzle_1.BadRequestError(`Cannot create document in "${index}":"${collection}" : ${error.reason}`);
52
- }
53
- }
54
- return successes[idx];
55
- }
56
- catch (exception) {
57
- const error = this.extractErrorByContent(content, exception.errors);
58
- if (error) {
59
- throw new kuzzle_1.BadRequestError(`Cannot create document in "${index}":"${collection}" : ${error.reason}`);
60
- }
61
- }
62
- }
63
- async replace(index, collection, _id, content, options) {
64
- const { idx, promise } = this.writer.addReplace(index, collection, content, _id, options);
65
- const { successes, errors } = await promise.promise;
66
- const error = this.extractErrorById(_id, errors);
67
- if (error) {
68
- throw new kuzzle_1.BadRequestError(`Cannot replace document "${index}":"${collection}":"${_id}": ${error.reason}`);
69
- }
70
- return successes[idx];
71
- }
72
- async createOrReplace(index, collection, _id, content, options) {
73
- const { idx, promise } = this.writer.addCreateOrReplace(index, collection, content, _id, options);
74
- const { successes, errors } = await promise.promise;
75
- const error = this.extractErrorById(_id, errors);
76
- if (error) {
77
- throw new kuzzle_1.BadRequestError(`Cannot create or replace document "${index}":"${collection}":"${_id}": ${error.reason}`);
78
- }
79
- return successes[idx];
80
- }
81
- async update(index, collection, _id, changes, options) {
82
- const { idx, promise } = this.writer.addUpdate(index, collection, changes, _id, options);
83
- const { successes, errors } = await promise.promise;
84
- const error = this.extractErrorById(_id, errors);
85
- if (error) {
86
- throw new kuzzle_1.BadRequestError(`Cannot update document "${index}":"${collection}":"${_id}": ${error.reason}`);
87
- }
88
- return successes[idx];
89
- }
90
- async get(index, collection, id) {
91
- const { promise } = this.writer.addGet(index, collection, undefined, id);
92
- const { successes } = await promise.promise;
93
- const document = successes.find(({ _id }) => _id === id);
94
- if (!document) {
95
- throw new kuzzle_1.NotFoundError(`Document "${index}":"${collection}":"${id}" not found`, 'services.storage.not_found');
96
- }
97
- return document;
98
- }
99
- async exists(index, collection, id) {
100
- const { idx, promise } = this.writer.addExists(index, collection, undefined, id);
101
- const { successes } = await promise.promise;
102
- return successes[idx];
103
- }
104
- async delete(index, collection, id) {
105
- const { idx, promise } = this.writer.addDelete(index, collection, undefined, id);
106
- const { successes, errors } = await promise.promise;
107
- const error = errors.find(({ _id }) => _id === id);
108
- if (error) {
109
- throw new kuzzle_1.NotFoundError(`Cannot delete document "${index}":"${collection}":"${id}" : ${error.reason}`);
110
- }
111
- return successes[idx];
112
- }
113
- }
114
- exports.BatchController = BatchController;
115
- //# sourceMappingURL=BatchController.js.map
@@ -1,110 +0,0 @@
1
- import { EmbeddedSDK, JSONObject } from 'kuzzle';
2
- import { BatchController } from './BatchController';
3
- import { InstrumentablePromise } from './InstrumentablePromise';
4
- /**
5
- * Map of index and collections with documents, options and associated promise
6
- */
7
- declare type IndexBuffer = {
8
- [index: string]: {
9
- [collection: string]: {
10
- documents: Array<{
11
- _id: string;
12
- body: JSONObject;
13
- }>;
14
- promise: InstrumentablePromise;
15
- options: JSONObject;
16
- };
17
- };
18
- };
19
- export declare class BatchBuffer {
20
- indexes: IndexBuffer;
21
- /**
22
- * Add a document to the buffer of a specific collection
23
- *
24
- * @param index Index name
25
- * @param collection Collection name
26
- * @param body Document content
27
- * @param _id Document ID
28
- * @param options Option object passed to the m* action
29
- *
30
- * @returns An object containing the index of the array of results and a promise resolving to the array of results
31
- */
32
- add(index: string, collection: string, body: JSONObject, _id?: string, options?: JSONObject): {
33
- idx: number;
34
- promise: InstrumentablePromise;
35
- };
36
- }
37
- /**
38
- * This class handle buffers for every supported API action of the document controller:
39
- * - create, update, createOrReplace, replace, get, exists, delete
40
- *
41
- * Each buffer is filled with documents to be write/get/delete into a collection.
42
- *
43
- * A timer will regularly execute the m* actions with the documents inside the buffers.
44
- *
45
- * If the interval is too big, buffers may contain too much documents for Kuzzle limits.
46
- * (e.g. "limits.documentsWriteCount" is 200 by default)
47
- */
48
- export declare class BatchWriter {
49
- private timer;
50
- private sdk;
51
- /**
52
- * Timer interval to execute m* API actions
53
- */
54
- private interval;
55
- /**
56
- * Max write buffer size. (Should match "limits.documentsWriteCount")
57
- */
58
- private maxWriteBufferSize;
59
- /**
60
- * Max read buffer size. (Should match "limits.documentsReadCount")
61
- */
62
- private maxReadBufferSize;
63
- private buffers;
64
- /**
65
- * Document Controller overload
66
- */
67
- document: BatchController;
68
- get addCreate(): any;
69
- get addUpdate(): any;
70
- get addGet(): any;
71
- get addExists(): any;
72
- get addDelete(): any;
73
- get addReplace(): any;
74
- get addCreateOrReplace(): any;
75
- /**
76
- * @param sdk Connected SDK
77
- * @param options.interval Timer interval in ms (50). Actions will be executed every {interval} ms
78
- * @param options.maxWriteBufferSize Max write buffer size (200). (Should match "limits.documentsWriteCount")
79
- * @param options.maxReadBufferSize Max read buffer size. (Should match "limits.documentsReadCount")
80
- */
81
- constructor(sdk: EmbeddedSDK, { interval, maxWriteBufferSize, maxReadBufferSize }?: {
82
- interval?: number;
83
- maxWriteBufferSize?: number;
84
- maxReadBufferSize?: number;
85
- });
86
- /**
87
- * Execute API actions with documents stored in the buffers.
88
- */
89
- execute(): Promise<void>;
90
- /**
91
- * Initialize the buffers and start the timer
92
- */
93
- begin(): void;
94
- /**
95
- * Execute pending actions from the buffers and stop the timer.
96
- */
97
- end(): Promise<void>;
98
- /**
99
- * Reset all the buffers
100
- */
101
- private prepareRound;
102
- private sendCreateBuffer;
103
- private sendUpdateBuffer;
104
- private sendReplaceBuffer;
105
- private sendCreateOrReplaceBuffer;
106
- private sendGetBuffer;
107
- private sendExistsBuffer;
108
- private sendDeleteBuffer;
109
- }
110
- export {};