-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathbase-class.ts
More file actions
517 lines (475 loc) · 16.3 KB
/
base-class.ts
File metadata and controls
517 lines (475 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
import pick from 'lodash/pick';
import last from 'lodash/last';
import chunk from 'lodash/chunk';
import isEmpty from 'lodash/isEmpty';
import entries from 'lodash/entries';
import isEqual from 'lodash/isEqual';
import omit from 'lodash/omit';
import {
log,
ManagementStack,
AssetData,
LocaleData,
PublishConfig,
FolderData,
ExtensionData,
EnvironmentData,
LabelData,
WebhookData,
WorkflowData,
RoleData,
CLIProgressManager,
configHandler
} from '@contentstack/cli-utilities';
import { ImportConfig, ModuleClassParams } from '../../types';
import cloneDeep from 'lodash/cloneDeep';
export type AdditionalKeys = {
backupDir: string;
};
export type CompleteProgressOptions = {
moduleName?: string;
customSuccessMessage?: string;
customWarningMessage?: string;
context?: Record<string, any>;
};
export type ApiModuleType =
| 'create-assets'
| 'replace-assets'
| 'publish-assets'
| 'create-assets-folder'
| 'create-extensions'
| 'update-extensions'
| 'create-locale'
| 'update-locale'
| 'create-gfs'
| 'create-cts'
| 'update-cts'
| 'update-gfs'
| 'create-environments'
| 'create-labels'
| 'update-labels'
| 'create-webhooks'
| 'create-workflows'
| 'create-custom-role'
| 'create-entries'
| 'update-entries'
| 'publish-entries'
| 'delete-entries'
| 'create-taxonomies'
| 'create-terms'
| 'import-taxonomy';
export type ApiOptions = {
uid?: string;
url?: string;
entity: ApiModuleType;
apiData?: Record<any, any> | any;
queryParam?: Record<any, any>;
resolve: (value: any) => Promise<void> | void;
reject: (error: any) => Promise<void> | void;
additionalInfo?: Record<any, any>;
includeParamOnCompletion?: boolean;
serializeData?: (input: ApiOptions) => any;
};
export type EnvType = {
processName: string;
totalCount?: number;
indexerCount?: number;
currentIndexer?: number;
apiParams?: ApiOptions;
concurrencyLimit?: number;
apiContent: Record<string, any>[];
};
export type CustomPromiseHandlerInput = {
index: number;
batchIndex: number;
element?: Record<string, unknown>;
apiParams?: ApiOptions;
isLastRequest: boolean;
};
export type CustomPromiseHandler = (input: CustomPromiseHandlerInput) => Promise<any>;
export default abstract class BaseClass {
readonly client: ManagementStack;
public importConfig: ImportConfig;
public modulesConfig: any;
protected progressManager: CLIProgressManager | null = null;
protected currentModuleName: string = '';
constructor({ importConfig, stackAPIClient }: Omit<ModuleClassParams, 'moduleName'>) {
this.client = stackAPIClient;
this.importConfig = importConfig;
this.modulesConfig = importConfig.modules;
}
get stack(): ManagementStack {
return this.client;
}
static printFinalSummary(): void {
CLIProgressManager.printGlobalSummary();
}
/**
* Create simple progress manager
*/
protected createSimpleProgress(moduleName: string, total?: number): CLIProgressManager {
this.currentModuleName = moduleName;
const logConfig = configHandler.get('log') || {};
const showConsoleLogs = logConfig.showConsoleLogs ?? false; // Default to true for better UX
this.progressManager = CLIProgressManager.createSimple(moduleName, total, showConsoleLogs);
return this.progressManager;
}
/**
* Create nested progress manager
*/
protected createNestedProgress(moduleName: string): CLIProgressManager {
this.currentModuleName = moduleName;
const logConfig = configHandler.get('log') || {};
const showConsoleLogs = logConfig.showConsoleLogs ?? false; // Default to true for better UX
this.progressManager = CLIProgressManager.createNested(moduleName, showConsoleLogs);
return this.progressManager;
}
/**
* Complete progress manager
*/
protected completeProgress(success: boolean = true, error?: string): void {
this.progressManager?.complete(success, error);
this.progressManager = null;
}
/**
* Complete progress and log success/warning message based on errors
* Checks the progress manager's failure count to determine if errors occurred
* @param options - Options object containing:
* - moduleName: The module name to generate the message (e.g., 'Content types', 'Entries')
* If not provided, uses this.currentModuleName
* - customSuccessMessage: Optional custom success message. If not provided, generates: "{moduleName} have been imported successfully!"
* - customWarningMessage: Optional custom warning message. If not provided, generates: "{moduleName} have been imported with some errors. Please check the logs for details."
* - context: Optional context for logging
*/
protected completeProgressWithMessage(options?: CompleteProgressOptions): void {
const logContext = options?.context || this.importConfig?.context || {};
const failureCount = this.progressManager?.getFailureCount() || 0;
const hasErrors = failureCount > 0;
const name = options?.moduleName || this.currentModuleName || 'Module';
// Generate default messages if not provided
const successMessage = options?.customSuccessMessage || `${name} have been imported successfully!`;
const warningMessage = options?.customWarningMessage || `${name} have been imported with some errors. Please check the logs for details.`;
this.completeProgress(true);
if (hasErrors) {
log.warn(warningMessage, logContext);
} else {
log.success(successMessage, logContext);
}
}
protected async withLoadingSpinner<T>(message: string, action: () => Promise<T>): Promise<T> {
const logConfig = configHandler.get('log') || {};
const showConsoleLogs = logConfig.showConsoleLogs ?? false;
if (showConsoleLogs) {
// If console logs are enabled, don't show spinner, just execute the action
return await action();
}
return await CLIProgressManager.withLoadingSpinner(message, action);
}
/**
* @method delay
* @param {number} ms number
* @returns {Promise} Promise<void>
*/
delay(ms: number): Promise<void> {
/* eslint-disable no-promise-executor-return */
return new Promise((resolve) => setTimeout(resolve, ms <= 0 ? 0 : ms));
}
/**
* @method makeConcurrentCall
* @param {Record<string, any>} env EnvType
* @param {CustomPromiseHandler} promisifyHandler CustomPromiseHandler
* @param {boolean} logBatchCompletionMsg boolean
* @returns {Promise} Promise<void>
*/
makeConcurrentCall(
env: EnvType,
promisifyHandler?: CustomPromiseHandler,
logBatchCompletionMsg = true,
): Promise<void> {
const {
apiParams,
apiContent,
processName,
indexerCount,
currentIndexer,
concurrencyLimit = this.importConfig.modules.apiConcurrency,
} = env;
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve) => {
let batchNo = 0;
let isLastRequest = false;
const batches: Array<Record<string, any>> = chunk(apiContent, concurrencyLimit);
/* eslint-disable no-promise-executor-return */
if (isEmpty(batches)) return resolve();
for (const [batchIndex, batch] of entries(batches)) {
batchNo += 1;
const allPromise = [];
const start = Date.now();
for (const [index, element] of entries(batch)) {
let promise = Promise.resolve();
isLastRequest = isEqual(last(batch as ArrayLike<any>), element) && isEqual(last(batches), batch);
if (promisifyHandler instanceof Function) {
promise = promisifyHandler({
apiParams,
isLastRequest,
element,
index: Number(index),
batchIndex: Number(batchIndex),
});
} else if (apiParams) {
apiParams.apiData = element;
promise = this.makeAPICall(apiParams, isLastRequest);
}
allPromise.push(promise);
}
/* eslint-disable no-await-in-loop */
await Promise.allSettled(allPromise);
/* eslint-disable no-await-in-loop */
await this.logMsgAndWaitIfRequired(
processName,
start,
batches.length,
batchNo,
logBatchCompletionMsg,
indexerCount,
currentIndexer,
);
if (isLastRequest) resolve();
}
});
}
/**
* @method logMsgAndWaitIfRequired
* @param {string} processName string
* @param {number} start number
* @param {number} batchNo - number
* @returns {Promise} Promise<void>
*/
async logMsgAndWaitIfRequired(
processName: string,
start: number,
totelBatches: number,
batchNo: number,
logBatchCompletionMsg = true,
indexerCount?: number,
currentIndexer?: number,
): Promise<void> {
const end = Date.now();
const exeTime = end - start;
if (logBatchCompletionMsg) {
let batchMsg = '';
// info: Batch No. 20 of import assets is complete
if (currentIndexer) batchMsg += `Current chunk processing is (${currentIndexer}/${indexerCount})`;
log.debug(`Batch No. (${batchNo}/${totelBatches}) of ${processName} is complete`, this.importConfig?.context);
}
if (this.importConfig.modules.assets.displayExecutionTime) {
console.log(
`Time taken to execute: ${exeTime} milliseconds; wait time: ${
exeTime < 1000 ? 1000 - exeTime : 0
} milliseconds`,
);
}
if (exeTime < 1000) await this.delay(1000 - exeTime);
}
/**
* @method makeAPICall
* @param {Record<string, any>} apiOptions - Api related params
* @param {Record<string, any>} isLastRequest - Boolean
* @return {Promise} Promise<void>
*/
makeAPICall(apiOptions: ApiOptions, isLastRequest = false): Promise<void> {
if (apiOptions.serializeData instanceof Function) {
apiOptions = apiOptions.serializeData(apiOptions);
}
const { uid, entity, reject, resolve, apiData, additionalInfo = {}, includeParamOnCompletion } = apiOptions;
const onSuccess = (response: any) =>
resolve({
response,
isLastRequest,
additionalInfo,
apiData: includeParamOnCompletion ? apiData : undefined,
});
const onReject = (error: Error) =>
reject({
error,
isLastRequest,
additionalInfo,
apiData: includeParamOnCompletion ? apiData : undefined,
});
if (
!apiData ||
(entity === 'publish-entries' && !apiData.entryUid) ||
(entity === 'update-extensions' && !apiData.uid)
) {
return Promise.resolve();
}
switch (entity) {
case 'create-assets-folder':
return this.stack
.asset()
.folder()
.create({ asset: pick(apiData, this.modulesConfig.assets.folderValidKeys) as FolderData })
.then(onSuccess)
.catch(onReject);
case 'create-assets':
return this.stack
.asset()
.create(pick(apiData, [...this.modulesConfig.assets.validKeys, 'upload']) as AssetData)
.then(onSuccess)
.catch(onReject);
case 'replace-assets':
return this.stack
.asset(uid)
.replace(pick(apiData, [...this.modulesConfig.assets.validKeys, 'upload']) as AssetData)
.then(onSuccess)
.catch(onReject);
case 'publish-assets':
return this.stack
.asset(uid)
.publish(pick(apiData, ['publishDetails']) as PublishConfig)
.then(onSuccess)
.catch(onReject);
case 'create-extensions':
return this.stack
.extension()
.create({ extension: omit(apiData, ['uid']) as ExtensionData })
.then(onSuccess)
.catch(onReject);
case 'update-extensions':
return this.stack
.extension(apiData.uid)
.fetch()
.then((extension) => {
extension.scope = apiData.scope;
return extension.update();
})
.then(onSuccess)
.catch(onReject);
case 'create-locale':
return this.stack
.locale()
.create({ locale: pick(apiData, ['name', 'code']) as LocaleData })
.then(onSuccess)
.catch(onReject);
case 'update-locale':
return this.stack
.locale(apiData.code)
.fetch()
.then((locale) => {
locale.name = apiData.name;
locale.fallback_locale = apiData.fallback_locale;
return locale.update();
})
.then(onSuccess)
.catch(onReject);
case 'create-cts':
return this.stack.contentType().create(apiData).then(onSuccess).catch(onReject);
case 'update-cts':
return apiData.update().then(onSuccess).catch(onReject);
case 'create-gfs':
return this.stack.globalField({ api_version: '3.2' }).create(apiData).then(onSuccess).catch(onReject);
case 'update-gfs':
let globalFieldUid = apiData.uid ?? apiData.global_field?.uid;
return this.stack
.globalField(globalFieldUid, { api_version: '3.2' })
.fetch()
.then(async (gf) => {
const { uid, ...updatePayload } = cloneDeep(apiData);
Object.assign(gf, updatePayload);
try {
const response = await gf.update();
return onSuccess(response);
} catch (error) {
return onReject(error);
}
})
.catch(onReject);
case 'create-environments':
return this.stack
.environment()
.create({ environment: omit(apiData, ['uid']) as EnvironmentData })
.then(onSuccess)
.catch(onReject);
case 'create-labels':
return this.stack
.label()
.create({ label: omit(apiData, ['uid']) as LabelData })
.then(onSuccess)
.catch(onReject);
case 'update-labels':
return this.stack
.label(apiData.uid)
.fetch()
.then(async (response) => {
response.parent = apiData.parent;
await response.update().then(onSuccess).catch(onReject);
})
.catch(onReject);
case 'create-webhooks':
return this.stack
.webhook()
.create({ webhook: omit(apiData, ['uid']) as WebhookData })
.then(onSuccess)
.catch(onReject);
case 'create-workflows':
return this.stack
.workflow()
.create({ workflow: apiData as WorkflowData })
.then(onSuccess)
.catch(onReject);
case 'create-custom-role':
return this.stack
.role()
.create({ role: apiData as RoleData })
.then(onSuccess)
.catch(onReject);
case 'create-entries':
if (additionalInfo[apiData?.uid]?.isLocalized) {
return apiData.update({ locale: additionalInfo.locale }).then(onSuccess).catch(onReject);
}
return this.stack
.contentType(additionalInfo.cTUid)
.entry()
.create({ entry: apiData }, { locale: additionalInfo.locale })
.then(onSuccess)
.catch(onReject);
case 'update-entries':
return apiData.update({ locale: additionalInfo.locale }).then(onSuccess).catch(onReject);
case 'publish-entries':
return this.stack
.contentType(additionalInfo.cTUid)
.entry(apiData.entryUid)
.publish({
publishDetails: { environments: apiData.environments, locales: apiData.locales },
locale: apiData.locales[0],
})
.then(onSuccess)
.catch(onReject);
case 'delete-entries':
return this.stack
.contentType(apiData.cTUid)
.entry(apiData.entryUid)
.delete({ locale: additionalInfo.locale })
.then(onSuccess)
.catch(onReject);
case 'create-taxonomies':
return this.stack.taxonomy().create({ taxonomy: apiData }).then(onSuccess).catch(onReject);
case 'create-terms':
return this.stack
.taxonomy(apiData.taxonomy_uid)
.terms()
.create({ term: apiData })
.then(onSuccess)
.catch(onReject);
case 'import-taxonomy':
if (!apiData || !apiData.filePath) {
return Promise.resolve();
}
const importParams = { taxonomy: apiData.filePath };
const importQueryParam = apiOptions.queryParam || {};
return this.stack.taxonomy(uid).import(importParams, importQueryParam).then(onSuccess).catch(onReject);
default:
return Promise.resolve();
}
}
}