@coveo/push-api-client 3.0.122 → 3.0.123

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 (129) hide show
  1. package/dist/APICore.js +47 -47
  2. package/dist/definitions/APICore.d.ts +18 -18
  3. package/dist/definitions/document.d.ts +124 -124
  4. package/dist/definitions/documentBuilder.d.ts +168 -168
  5. package/dist/definitions/documentBuilder.spec.d.ts +1 -1
  6. package/dist/definitions/environment.d.ts +16 -16
  7. package/dist/definitions/errors/baseError.d.ts +4 -4
  8. package/dist/definitions/errors/fieldErrors.d.ts +18 -18
  9. package/dist/definitions/errors/index.d.ts +3 -3
  10. package/dist/definitions/errors/privilegeError.d.ts +6 -6
  11. package/dist/definitions/errors/validatorErrors.d.ts +20 -20
  12. package/dist/definitions/fieldAnalyser/fieldAnalyser.d.ts +36 -36
  13. package/dist/definitions/fieldAnalyser/fieldAnalyser.spec.d.ts +1 -1
  14. package/dist/definitions/fieldAnalyser/fieldStore.d.ts +5 -5
  15. package/dist/definitions/fieldAnalyser/fieldUtils.d.ts +6 -6
  16. package/dist/definitions/fieldAnalyser/fieldsUtils.spec.d.ts +1 -1
  17. package/dist/definitions/fieldAnalyser/inconsistencies.d.ts +5 -5
  18. package/dist/definitions/fieldAnalyser/inconsistencies.spec.d.ts +1 -1
  19. package/dist/definitions/fieldAnalyser/typeUtils.d.ts +3 -3
  20. package/dist/definitions/fieldAnalyser/typeUtils.spec.d.ts +1 -1
  21. package/dist/definitions/help/file.d.ts +3 -3
  22. package/dist/definitions/help/file.spec.d.ts +1 -1
  23. package/dist/definitions/help/fileConsumer.d.ts +31 -31
  24. package/dist/definitions/help/fileConsumer.spec.d.ts +1 -1
  25. package/dist/definitions/help/fileContainer.d.ts +8 -8
  26. package/dist/definitions/help/fileContainer.spec.d.ts +1 -1
  27. package/dist/definitions/help/function.d.ts +1 -1
  28. package/dist/definitions/help/generator.d.ts +11 -11
  29. package/dist/definitions/help/generator.spec.d.ts +1 -1
  30. package/dist/definitions/help/urlUtils.d.ts +27 -27
  31. package/dist/definitions/help/urlUtils.spec.d.ts +1 -1
  32. package/dist/definitions/index.d.ts +14 -14
  33. package/dist/definitions/interfaces.d.ts +70 -70
  34. package/dist/definitions/localtest.d.ts +1 -1
  35. package/dist/definitions/permissionSetBuilder.d.ts +34 -34
  36. package/dist/definitions/permissionSetBuilder.spec.d.ts +1 -1
  37. package/dist/definitions/securityIdentityBuilder.d.ts +105 -105
  38. package/dist/definitions/securityIdentityBuilder.spec.d.ts +1 -1
  39. package/dist/definitions/source/batchUploadDocumentsFromFile.d.ts +11 -11
  40. package/dist/definitions/source/batchUploadDocumentsFromFile.spec.d.ts +1 -1
  41. package/dist/definitions/source/catalog.d.ts +70 -70
  42. package/dist/definitions/source/catalog.spec.d.ts +1 -1
  43. package/dist/definitions/source/documentUploader.d.ts +11 -11
  44. package/dist/definitions/source/documentUploader.spec.d.ts +1 -1
  45. package/dist/definitions/source/push.d.ts +87 -87
  46. package/dist/definitions/source/push.spec.d.ts +1 -1
  47. package/dist/definitions/source/securityIdenty.d.ts +43 -43
  48. package/dist/definitions/uploadStrategy/fileContainerStrategy.d.ts +23 -23
  49. package/dist/definitions/uploadStrategy/fileContainerStrategy.spec.d.ts +1 -1
  50. package/dist/definitions/uploadStrategy/index.d.ts +3 -3
  51. package/dist/definitions/uploadStrategy/strategy.d.ts +23 -23
  52. package/dist/definitions/uploadStrategy/streamChunkStrategy.d.ts +28 -28
  53. package/dist/definitions/uploadStrategy/streamChunkStrategy.spec.d.ts +1 -1
  54. package/dist/definitions/validation/caseInsensitiveDocument.d.ts +13 -13
  55. package/dist/definitions/validation/knownKey.d.ts +10 -10
  56. package/dist/definitions/validation/parseFile.d.ts +4 -4
  57. package/dist/definitions/validation/parseFile.spec.d.ts +1 -1
  58. package/dist/definitions/validation/parsePermissions.d.ts +5 -5
  59. package/dist/definitions/validation/parsePermissions.spec.d.ts +1 -1
  60. package/dist/definitions/validation/preconditions/apiKeyPrivilege.d.ts +3 -3
  61. package/dist/definitions/validation/preconditions/apiKeyPrivilege.spec.d.ts +1 -1
  62. package/dist/definitions/validation/preconditions/platformPrivilege.d.ts +7 -7
  63. package/dist/definitions/validation/requiredKeyValidator.d.ts +17 -17
  64. package/dist/definitions/validation/transformers/transformer.d.ts +31 -31
  65. package/dist/definitions/validation/transformers/transformer.spec.d.ts +1 -1
  66. package/dist/document.js +2 -2
  67. package/dist/documentBuilder.js +292 -292
  68. package/dist/documentBuilder.spec.js +191 -191
  69. package/dist/environment.js +41 -41
  70. package/dist/errors/baseError.js +10 -10
  71. package/dist/errors/fieldErrors.js +42 -42
  72. package/dist/errors/index.js +19 -19
  73. package/dist/errors/privilegeError.js +12 -12
  74. package/dist/errors/validatorErrors.js +40 -40
  75. package/dist/fieldAnalyser/fieldAnalyser.js +95 -95
  76. package/dist/fieldAnalyser/fieldAnalyser.spec.js +230 -230
  77. package/dist/fieldAnalyser/fieldStore.js +21 -21
  78. package/dist/fieldAnalyser/fieldUtils.js +41 -41
  79. package/dist/fieldAnalyser/fieldsUtils.spec.js +116 -116
  80. package/dist/fieldAnalyser/inconsistencies.js +14 -14
  81. package/dist/fieldAnalyser/inconsistencies.spec.js +40 -40
  82. package/dist/fieldAnalyser/typeUtils.js +61 -61
  83. package/dist/fieldAnalyser/typeUtils.spec.js +142 -142
  84. package/dist/help/file.js +37 -37
  85. package/dist/help/file.spec.js +67 -67
  86. package/dist/help/fileConsumer.js +150 -150
  87. package/dist/help/fileConsumer.spec.js +153 -153
  88. package/dist/help/fileContainer.js +48 -48
  89. package/dist/help/fileContainer.spec.js +65 -65
  90. package/dist/help/function.js +5 -5
  91. package/dist/help/generator.js +32 -32
  92. package/dist/help/generator.spec.js +82 -82
  93. package/dist/help/urlUtils.js +42 -42
  94. package/dist/help/urlUtils.spec.js +41 -41
  95. package/dist/index.js +38 -38
  96. package/dist/interfaces.js +2 -2
  97. package/dist/localtest.js +55 -55
  98. package/dist/permissionSetBuilder.js +58 -58
  99. package/dist/permissionSetBuilder.spec.js +68 -68
  100. package/dist/securityIdentityBuilder.js +128 -128
  101. package/dist/securityIdentityBuilder.spec.js +50 -50
  102. package/dist/source/batchUploadDocumentsFromFile.js +46 -46
  103. package/dist/source/batchUploadDocumentsFromFile.spec.js +145 -145
  104. package/dist/source/catalog.js +111 -111
  105. package/dist/source/catalog.spec.js +64 -64
  106. package/dist/source/documentUploader.js +45 -45
  107. package/dist/source/documentUploader.spec.js +118 -118
  108. package/dist/source/push.js +140 -140
  109. package/dist/source/push.spec.js +152 -152
  110. package/dist/source/securityIdenty.js +57 -57
  111. package/dist/uploadStrategy/fileContainerStrategy.js +32 -32
  112. package/dist/uploadStrategy/fileContainerStrategy.spec.js +86 -86
  113. package/dist/uploadStrategy/index.js +19 -19
  114. package/dist/uploadStrategy/strategy.js +2 -2
  115. package/dist/uploadStrategy/streamChunkStrategy.js +52 -52
  116. package/dist/uploadStrategy/streamChunkStrategy.spec.js +77 -77
  117. package/dist/validation/caseInsensitiveDocument.js +31 -31
  118. package/dist/validation/knownKey.js +37 -37
  119. package/dist/validation/parseFile.js +120 -120
  120. package/dist/validation/parseFile.spec.js +96 -96
  121. package/dist/validation/parsePermissions.js +118 -118
  122. package/dist/validation/parsePermissions.spec.js +86 -86
  123. package/dist/validation/preconditions/apiKeyPrivilege.js +20 -20
  124. package/dist/validation/preconditions/apiKeyPrivilege.spec.js +66 -66
  125. package/dist/validation/preconditions/platformPrivilege.js +32 -32
  126. package/dist/validation/requiredKeyValidator.js +61 -61
  127. package/dist/validation/transformers/transformer.js +51 -51
  128. package/dist/validation/transformers/transformer.spec.js +21 -21
  129. package/package.json +1 -1
@@ -1,151 +1,151 @@
1
- "use strict";
2
- var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
3
- var __asyncValues = (this && this.__asyncValues) || function (o) {
4
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
5
- var m = o[Symbol.asyncIterator], i;
6
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
7
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
8
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
9
- };
10
- var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {
11
- var i, p;
12
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
13
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
14
- };
15
- var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
16
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
17
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
18
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
19
- function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
20
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
21
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
22
- function fulfill(value) { resume("next", value); }
23
- function reject(value) { resume("throw", value); }
24
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
25
- };
26
- Object.defineProperty(exports, "__esModule", { value: true });
27
- exports.FileConsumer = void 0;
28
- const parseFile_1 = require("../validation/parseFile");
29
- const path_1 = require("path");
30
- const generator_1 = require("./generator");
31
- const bueno_1 = require("@coveo/bueno");
32
- /**
33
- * Util class to help injesting documents through a list of files and uploading generated document batches.
34
- */
35
- class FileConsumer {
36
- /**
37
- * Creates an instance of FileConsumer.
38
- * @param {(batch: BatchUpdateDocuments) => Promise<Response>} upload the upload operation to apply to every document batch
39
- * @param {Required<ConcurrentProcessing>} processingConfig
40
- */
41
- constructor(upload, processingConfig) {
42
- this.upload = upload;
43
- this.processingConfig = processingConfig;
44
- this.cbSuccess = () => { };
45
- this.cbFail = () => { };
46
- }
47
- async consume(files, options) {
48
- const fileNames = files.map((path) => (0, path_1.basename)(path));
49
- const { chunksToUpload, close } = this.splitByChunkAndUpload(fileNames);
50
- const docBuilderGenerator = function* (docBuilders) {
51
- for (const upload of chunksToUpload(docBuilders)) {
52
- yield upload();
53
- }
54
- };
55
- // parallelize uploads across multiple files
56
- const fileGenerator = function () {
57
- return __asyncGenerator(this, arguments, function* () {
58
- for (const filePath of files.values()) {
59
- const docBuilders = yield __await((0, parseFile_1.parseAndGetDocumentBuilderFromJSONDocument)(filePath, options));
60
- yield __await(yield* __asyncDelegator(__asyncValues(docBuilderGenerator(docBuilders))));
61
- }
62
- });
63
- };
64
- await (0, generator_1.consumeGenerator)(fileGenerator.bind(this), this.processingConfig.maxConcurrent);
65
- await close();
66
- }
67
- onSuccess(callback) {
68
- this.cbSuccess = callback;
69
- }
70
- onError(callback) {
71
- this.cbFail = callback;
72
- }
73
- splitByChunkAndUpload(fileNames, accumulator = this.accumulator) {
74
- const chunksToUpload = (documentBuilders) => {
75
- const batchesToUpload = [];
76
- for (const docBuilder of documentBuilders) {
77
- const sizeOfDoc = Buffer.byteLength(JSON.stringify(docBuilder.marshal()));
78
- if (accumulator.size + sizeOfDoc >= FileConsumer.maxContentLength) {
79
- const chunks = accumulator.chunks;
80
- if (chunks.length > 0) {
81
- batchesToUpload.push(() => this.uploadBatch(chunks, fileNames));
82
- }
83
- accumulator.chunks = [docBuilder];
84
- accumulator.size = sizeOfDoc;
85
- }
86
- else {
87
- accumulator.size += sizeOfDoc;
88
- accumulator.chunks.push(docBuilder);
89
- }
90
- }
91
- return batchesToUpload;
92
- };
93
- const close = async () => {
94
- await this.uploadBatch(accumulator.chunks, fileNames);
95
- };
96
- return { chunksToUpload, close };
97
- }
98
- set expectedDocumentCount(count) {
99
- this._totalDocumentCount = count;
100
- this._remainingDocumentCount = count;
101
- }
102
- getRemainingDocumentCount(batch) {
103
- if (this._remainingDocumentCount === undefined) {
104
- return;
105
- }
106
- return (this._remainingDocumentCount -= batch.length);
107
- }
108
- async uploadBatch(batch, fileNames) {
109
- let res;
110
- const progress = this.getProgress(batch);
111
- try {
112
- res = await this.upload({
113
- addOrUpdate: batch,
114
- delete: [],
115
- });
116
- }
117
- catch (error) {
118
- this.cbFail(error, {
119
- files: fileNames,
120
- batch,
121
- progress,
122
- });
123
- }
124
- this.cbSuccess({
125
- files: fileNames,
126
- batch,
127
- res,
128
- progress,
129
- });
130
- }
131
- getProgress(batch) {
132
- const remainingDocumentCount = this.getRemainingDocumentCount(batch);
133
- if ((0, bueno_1.isUndefined)(remainingDocumentCount) ||
134
- (0, bueno_1.isUndefined)(this._totalDocumentCount)) {
135
- return;
136
- }
137
- return {
138
- remainingDocumentCount,
139
- totalDocumentCount: this._totalDocumentCount,
140
- };
141
- }
142
- get accumulator() {
143
- return {
144
- size: 0,
145
- chunks: [],
146
- };
147
- }
148
- }
149
- exports.FileConsumer = FileConsumer;
150
- FileConsumer.maxContentLength = 5 * 1024 * 1024;
1
+ "use strict";
2
+ var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
3
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
4
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
5
+ var m = o[Symbol.asyncIterator], i;
6
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
7
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
8
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
9
+ };
10
+ var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {
11
+ var i, p;
12
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
13
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
14
+ };
15
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
16
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
17
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
18
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
19
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
20
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
21
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
22
+ function fulfill(value) { resume("next", value); }
23
+ function reject(value) { resume("throw", value); }
24
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.FileConsumer = void 0;
28
+ const parseFile_1 = require("../validation/parseFile");
29
+ const path_1 = require("path");
30
+ const generator_1 = require("./generator");
31
+ const bueno_1 = require("@coveo/bueno");
32
+ /**
33
+ * Util class to help injesting documents through a list of files and uploading generated document batches.
34
+ */
35
+ class FileConsumer {
36
+ /**
37
+ * Creates an instance of FileConsumer.
38
+ * @param {(batch: BatchUpdateDocuments) => Promise<Response>} upload the upload operation to apply to every document batch
39
+ * @param {Required<ConcurrentProcessing>} processingConfig
40
+ */
41
+ constructor(upload, processingConfig) {
42
+ this.upload = upload;
43
+ this.processingConfig = processingConfig;
44
+ this.cbSuccess = () => { };
45
+ this.cbFail = () => { };
46
+ }
47
+ async consume(files, options) {
48
+ const fileNames = files.map((path) => (0, path_1.basename)(path));
49
+ const { chunksToUpload, close } = this.splitByChunkAndUpload(fileNames);
50
+ const docBuilderGenerator = function* (docBuilders) {
51
+ for (const upload of chunksToUpload(docBuilders)) {
52
+ yield upload();
53
+ }
54
+ };
55
+ // parallelize uploads across multiple files
56
+ const fileGenerator = function () {
57
+ return __asyncGenerator(this, arguments, function* () {
58
+ for (const filePath of files.values()) {
59
+ const docBuilders = yield __await((0, parseFile_1.parseAndGetDocumentBuilderFromJSONDocument)(filePath, options));
60
+ yield __await(yield* __asyncDelegator(__asyncValues(docBuilderGenerator(docBuilders))));
61
+ }
62
+ });
63
+ };
64
+ await (0, generator_1.consumeGenerator)(fileGenerator.bind(this), this.processingConfig.maxConcurrent);
65
+ await close();
66
+ }
67
+ onSuccess(callback) {
68
+ this.cbSuccess = callback;
69
+ }
70
+ onError(callback) {
71
+ this.cbFail = callback;
72
+ }
73
+ splitByChunkAndUpload(fileNames, accumulator = this.accumulator) {
74
+ const chunksToUpload = (documentBuilders) => {
75
+ const batchesToUpload = [];
76
+ for (const docBuilder of documentBuilders) {
77
+ const sizeOfDoc = Buffer.byteLength(JSON.stringify(docBuilder.marshal()));
78
+ if (accumulator.size + sizeOfDoc >= FileConsumer.maxContentLength) {
79
+ const chunks = accumulator.chunks;
80
+ if (chunks.length > 0) {
81
+ batchesToUpload.push(() => this.uploadBatch(chunks, fileNames));
82
+ }
83
+ accumulator.chunks = [docBuilder];
84
+ accumulator.size = sizeOfDoc;
85
+ }
86
+ else {
87
+ accumulator.size += sizeOfDoc;
88
+ accumulator.chunks.push(docBuilder);
89
+ }
90
+ }
91
+ return batchesToUpload;
92
+ };
93
+ const close = async () => {
94
+ await this.uploadBatch(accumulator.chunks, fileNames);
95
+ };
96
+ return { chunksToUpload, close };
97
+ }
98
+ set expectedDocumentCount(count) {
99
+ this._totalDocumentCount = count;
100
+ this._remainingDocumentCount = count;
101
+ }
102
+ getRemainingDocumentCount(batch) {
103
+ if (this._remainingDocumentCount === undefined) {
104
+ return;
105
+ }
106
+ return (this._remainingDocumentCount -= batch.length);
107
+ }
108
+ async uploadBatch(batch, fileNames) {
109
+ let res;
110
+ const progress = this.getProgress(batch);
111
+ try {
112
+ res = await this.upload({
113
+ addOrUpdate: batch,
114
+ delete: [],
115
+ });
116
+ }
117
+ catch (error) {
118
+ this.cbFail(error, {
119
+ files: fileNames,
120
+ batch,
121
+ progress,
122
+ });
123
+ }
124
+ this.cbSuccess({
125
+ files: fileNames,
126
+ batch,
127
+ res,
128
+ progress,
129
+ });
130
+ }
131
+ getProgress(batch) {
132
+ const remainingDocumentCount = this.getRemainingDocumentCount(batch);
133
+ if ((0, bueno_1.isUndefined)(remainingDocumentCount) ||
134
+ (0, bueno_1.isUndefined)(this._totalDocumentCount)) {
135
+ return;
136
+ }
137
+ return {
138
+ remainingDocumentCount,
139
+ totalDocumentCount: this._totalDocumentCount,
140
+ };
141
+ }
142
+ get accumulator() {
143
+ return {
144
+ size: 0,
145
+ chunks: [],
146
+ };
147
+ }
148
+ }
149
+ exports.FileConsumer = FileConsumer;
150
+ FileConsumer.maxContentLength = 5 * 1024 * 1024;
151
151
  //# sourceMappingURL=fileConsumer.js.map
@@ -1,154 +1,154 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- jest.mock('../validation/parseFile');
4
- const __1 = require("..");
5
- const fileConsumer_1 = require("./fileConsumer");
6
- const parseFile_1 = require("../validation/parseFile");
7
- const mockedParse = jest.mocked(parseFile_1.parseAndGetDocumentBuilderFromJSONDocument);
8
- // generating 5 documents of 2 mb each
9
- mockedParse.mockResolvedValue(generateDocBuilderBatch(5, 2));
10
- function generateDocBuilderBatch(documentCount, documentSize) {
11
- let counter = 1;
12
- const randomCharacter = '#';
13
- const bytes = documentSize * 1024 * 1024;
14
- const data = Buffer.alloc(bytes, randomCharacter).toString();
15
- const docBuilderFactory = () => new __1.DocumentBuilder(`https://url.com/${counter++}`, 'title').withData(data);
16
- return [...Array(documentCount)].map(docBuilderFactory);
17
- }
18
- describe('FileConsumer', () => {
19
- let fileConsumer;
20
- const fakeUpload = jest.fn();
21
- const singleEntry = ['foo.json'];
22
- const entries = ['bar.json', 'baz.json'];
23
- describe('when upload is successful', () => {
24
- beforeEach(() => {
25
- fileConsumer = new fileConsumer_1.FileConsumer(fakeUpload, { maxConcurrent: 10 });
26
- fakeUpload.mockResolvedValue({
27
- status: 202,
28
- statusText: 'All good',
29
- });
30
- });
31
- afterEach(() => {
32
- fakeUpload.mockReset();
33
- });
34
- it('should call the success callback', async () => {
35
- const mockedHandleSuccess = jest.fn();
36
- fileConsumer.onSuccess(mockedHandleSuccess);
37
- await fileConsumer.consume(entries);
38
- expect(mockedHandleSuccess).toHaveBeenCalled();
39
- });
40
- it('should not call the error callback', async () => {
41
- const mockedHandleError = jest.fn();
42
- fileConsumer.onError(mockedHandleError);
43
- await fileConsumer.consume(entries);
44
- expect(mockedHandleError).not.toHaveBeenCalled();
45
- });
46
- it('should only push JSON files', async () => {
47
- const expectedSequence = [
48
- 'https://url.com/1',
49
- 'https://url.com/2',
50
- 'https://url.com/3',
51
- 'https://url.com/4',
52
- 'https://url.com/5',
53
- ].values();
54
- const handleBatchUpload = (data) => {
55
- for (const element of data.batch) {
56
- const documentBuilder = element;
57
- const { documentId } = documentBuilder.marshal();
58
- expect(documentId).toEqual(expectedSequence.next().value);
59
- }
60
- };
61
- fileConsumer.onSuccess(handleBatchUpload);
62
- await fileConsumer.consume(singleEntry);
63
- });
64
- describe.each([
65
- {
66
- // 1 file with 5 documents of 2MB each => 10MB to upload => 3 batches: [4MB] [4MB] [2MB]
67
- title: 'when consume a single file',
68
- sequence: [2, 2, 1],
69
- entries: ['foo.json'],
70
- },
71
- {
72
- // 2 files with 5 documents each weighing 2MB => 20MB to upload => 5 batches: [4MB] [4MB] [4MB] [4MB] [4MB]
73
- title: 'when consume 2 files',
74
- sequence: [2, 2, 2, 2, 2],
75
- entries: ['foo.json', 'bar.json'],
76
- },
77
- ])('$title', ({ sequence, entries }) => {
78
- it(`should create ${sequence.length} batches`, async () => {
79
- const batchOrder = sequence.values();
80
- const handleBatchUpload = (data) => expect(data.batch.length).toEqual(batchOrder.next().value);
81
- fileConsumer.onSuccess(handleBatchUpload);
82
- await fileConsumer.consume(entries);
83
- });
84
- it(`should call callback ${sequence.length} times`, async () => {
85
- const mockedHandleSuccess = jest.fn();
86
- fileConsumer.onSuccess(mockedHandleSuccess);
87
- await fileConsumer.consume(entries);
88
- expect(mockedHandleSuccess).toHaveBeenCalledTimes(sequence.length);
89
- });
90
- });
91
- describe('when the upload progress is returned', () => {
92
- const mockedHandleSuccess = jest.fn();
93
- const documentCount = 5;
94
- beforeEach(async () => {
95
- fileConsumer.expectedDocumentCount = documentCount;
96
- fileConsumer.onSuccess(mockedHandleSuccess);
97
- await fileConsumer.consume(singleEntry);
98
- });
99
- it('should call callback on every batch upload', async () => {
100
- expect(mockedHandleSuccess).toHaveBeenCalledTimes(3);
101
- });
102
- it('should return remaining and total documents at each call', async () => {
103
- expect(mockedHandleSuccess).toHaveBeenNthCalledWith(1, expect.objectContaining({
104
- progress: { remainingDocumentCount: 3, totalDocumentCount: 5 },
105
- }));
106
- expect(mockedHandleSuccess).toHaveBeenNthCalledWith(2, expect.objectContaining({
107
- progress: { remainingDocumentCount: 1, totalDocumentCount: 5 },
108
- }));
109
- expect(mockedHandleSuccess).toHaveBeenNthCalledWith(3, expect.objectContaining({
110
- progress: { remainingDocumentCount: 0, totalDocumentCount: 5 },
111
- }));
112
- });
113
- });
114
- });
115
- describe('when upload is in error', () => {
116
- let fileConsumer;
117
- beforeEach(() => {
118
- fileConsumer = new fileConsumer_1.FileConsumer(fakeUpload, { maxConcurrent: 10 });
119
- fakeUpload.mockRejectedValueOnce({
120
- status: 412,
121
- statusText: 'BAD_REQUEST',
122
- });
123
- });
124
- it('should return the number of remaining documents', async () => {
125
- const mockedHandleError = jest.fn();
126
- const documentCount = 5;
127
- fileConsumer.expectedDocumentCount = documentCount;
128
- fileConsumer.onError(mockedHandleError);
129
- await fileConsumer.consume(singleEntry);
130
- expect(mockedHandleError).toHaveBeenCalledTimes(1);
131
- expect(mockedHandleError).toHaveBeenCalledWith({
132
- status: 412,
133
- statusText: 'BAD_REQUEST',
134
- }, expect.objectContaining({
135
- progress: { remainingDocumentCount: 3, totalDocumentCount: 5 },
136
- }) // 2 out of 5 document processed... 3 remaiming
137
- );
138
- });
139
- it('should call the error callback', async () => {
140
- const mockedHandleError = jest.fn();
141
- fileConsumer.onError(mockedHandleError);
142
- await fileConsumer.consume(entries);
143
- expect(mockedHandleError).toHaveBeenCalled();
144
- });
145
- it('should call the error callback', async () => {
146
- const handleBatchError = (err) => {
147
- expect(err).toEqual({ status: 412, statusText: 'BAD_REQUEST' });
148
- };
149
- fileConsumer.onError(handleBatchError);
150
- await fileConsumer.consume(entries);
151
- });
152
- });
153
- });
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ jest.mock('../validation/parseFile');
4
+ const __1 = require("..");
5
+ const fileConsumer_1 = require("./fileConsumer");
6
+ const parseFile_1 = require("../validation/parseFile");
7
+ const mockedParse = jest.mocked(parseFile_1.parseAndGetDocumentBuilderFromJSONDocument);
8
+ // generating 5 documents of 2 mb each
9
+ mockedParse.mockResolvedValue(generateDocBuilderBatch(5, 2));
10
+ function generateDocBuilderBatch(documentCount, documentSize) {
11
+ let counter = 1;
12
+ const randomCharacter = '#';
13
+ const bytes = documentSize * 1024 * 1024;
14
+ const data = Buffer.alloc(bytes, randomCharacter).toString();
15
+ const docBuilderFactory = () => new __1.DocumentBuilder(`https://url.com/${counter++}`, 'title').withData(data);
16
+ return [...Array(documentCount)].map(docBuilderFactory);
17
+ }
18
+ describe('FileConsumer', () => {
19
+ let fileConsumer;
20
+ const fakeUpload = jest.fn();
21
+ const singleEntry = ['foo.json'];
22
+ const entries = ['bar.json', 'baz.json'];
23
+ describe('when upload is successful', () => {
24
+ beforeEach(() => {
25
+ fileConsumer = new fileConsumer_1.FileConsumer(fakeUpload, { maxConcurrent: 10 });
26
+ fakeUpload.mockResolvedValue({
27
+ status: 202,
28
+ statusText: 'All good',
29
+ });
30
+ });
31
+ afterEach(() => {
32
+ fakeUpload.mockReset();
33
+ });
34
+ it('should call the success callback', async () => {
35
+ const mockedHandleSuccess = jest.fn();
36
+ fileConsumer.onSuccess(mockedHandleSuccess);
37
+ await fileConsumer.consume(entries);
38
+ expect(mockedHandleSuccess).toHaveBeenCalled();
39
+ });
40
+ it('should not call the error callback', async () => {
41
+ const mockedHandleError = jest.fn();
42
+ fileConsumer.onError(mockedHandleError);
43
+ await fileConsumer.consume(entries);
44
+ expect(mockedHandleError).not.toHaveBeenCalled();
45
+ });
46
+ it('should only push JSON files', async () => {
47
+ const expectedSequence = [
48
+ 'https://url.com/1',
49
+ 'https://url.com/2',
50
+ 'https://url.com/3',
51
+ 'https://url.com/4',
52
+ 'https://url.com/5',
53
+ ].values();
54
+ const handleBatchUpload = (data) => {
55
+ for (const element of data.batch) {
56
+ const documentBuilder = element;
57
+ const { documentId } = documentBuilder.marshal();
58
+ expect(documentId).toEqual(expectedSequence.next().value);
59
+ }
60
+ };
61
+ fileConsumer.onSuccess(handleBatchUpload);
62
+ await fileConsumer.consume(singleEntry);
63
+ });
64
+ describe.each([
65
+ {
66
+ // 1 file with 5 documents of 2MB each => 10MB to upload => 3 batches: [4MB] [4MB] [2MB]
67
+ title: 'when consume a single file',
68
+ sequence: [2, 2, 1],
69
+ entries: ['foo.json'],
70
+ },
71
+ {
72
+ // 2 files with 5 documents each weighing 2MB => 20MB to upload => 5 batches: [4MB] [4MB] [4MB] [4MB] [4MB]
73
+ title: 'when consume 2 files',
74
+ sequence: [2, 2, 2, 2, 2],
75
+ entries: ['foo.json', 'bar.json'],
76
+ },
77
+ ])('$title', ({ sequence, entries }) => {
78
+ it(`should create ${sequence.length} batches`, async () => {
79
+ const batchOrder = sequence.values();
80
+ const handleBatchUpload = (data) => expect(data.batch.length).toEqual(batchOrder.next().value);
81
+ fileConsumer.onSuccess(handleBatchUpload);
82
+ await fileConsumer.consume(entries);
83
+ });
84
+ it(`should call callback ${sequence.length} times`, async () => {
85
+ const mockedHandleSuccess = jest.fn();
86
+ fileConsumer.onSuccess(mockedHandleSuccess);
87
+ await fileConsumer.consume(entries);
88
+ expect(mockedHandleSuccess).toHaveBeenCalledTimes(sequence.length);
89
+ });
90
+ });
91
+ describe('when the upload progress is returned', () => {
92
+ const mockedHandleSuccess = jest.fn();
93
+ const documentCount = 5;
94
+ beforeEach(async () => {
95
+ fileConsumer.expectedDocumentCount = documentCount;
96
+ fileConsumer.onSuccess(mockedHandleSuccess);
97
+ await fileConsumer.consume(singleEntry);
98
+ });
99
+ it('should call callback on every batch upload', async () => {
100
+ expect(mockedHandleSuccess).toHaveBeenCalledTimes(3);
101
+ });
102
+ it('should return remaining and total documents at each call', async () => {
103
+ expect(mockedHandleSuccess).toHaveBeenNthCalledWith(1, expect.objectContaining({
104
+ progress: { remainingDocumentCount: 3, totalDocumentCount: 5 },
105
+ }));
106
+ expect(mockedHandleSuccess).toHaveBeenNthCalledWith(2, expect.objectContaining({
107
+ progress: { remainingDocumentCount: 1, totalDocumentCount: 5 },
108
+ }));
109
+ expect(mockedHandleSuccess).toHaveBeenNthCalledWith(3, expect.objectContaining({
110
+ progress: { remainingDocumentCount: 0, totalDocumentCount: 5 },
111
+ }));
112
+ });
113
+ });
114
+ });
115
+ describe('when upload is in error', () => {
116
+ let fileConsumer;
117
+ beforeEach(() => {
118
+ fileConsumer = new fileConsumer_1.FileConsumer(fakeUpload, { maxConcurrent: 10 });
119
+ fakeUpload.mockRejectedValueOnce({
120
+ status: 412,
121
+ statusText: 'BAD_REQUEST',
122
+ });
123
+ });
124
+ it('should return the number of remaining documents', async () => {
125
+ const mockedHandleError = jest.fn();
126
+ const documentCount = 5;
127
+ fileConsumer.expectedDocumentCount = documentCount;
128
+ fileConsumer.onError(mockedHandleError);
129
+ await fileConsumer.consume(singleEntry);
130
+ expect(mockedHandleError).toHaveBeenCalledTimes(1);
131
+ expect(mockedHandleError).toHaveBeenCalledWith({
132
+ status: 412,
133
+ statusText: 'BAD_REQUEST',
134
+ }, expect.objectContaining({
135
+ progress: { remainingDocumentCount: 3, totalDocumentCount: 5 },
136
+ }) // 2 out of 5 document processed... 3 remaiming
137
+ );
138
+ });
139
+ it('should call the error callback', async () => {
140
+ const mockedHandleError = jest.fn();
141
+ fileConsumer.onError(mockedHandleError);
142
+ await fileConsumer.consume(entries);
143
+ expect(mockedHandleError).toHaveBeenCalled();
144
+ });
145
+ it('should call the error callback', async () => {
146
+ const handleBatchError = (err) => {
147
+ expect(err).toEqual({ status: 412, statusText: 'BAD_REQUEST' });
148
+ };
149
+ fileConsumer.onError(handleBatchError);
150
+ await fileConsumer.consume(entries);
151
+ });
152
+ });
153
+ });
154
154
  //# sourceMappingURL=fileConsumer.spec.js.map