-
Notifications
You must be signed in to change notification settings - Fork 36
/
MetadataType.js
2129 lines (2045 loc) · 90.4 KB
/
MetadataType.js
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/* eslint no-unused-vars:off */
/*
* README no-unused-vars is reduced to WARNING here as this file is a template
* for all metadata types and methods often define params that are not used
* in the generic version of the method
*/
const TYPE = require('../../types/mcdev.d');
const Util = require('../util/util');
const File = require('../util/file');
const cache = require('../util/cache');
const deepEqual = require('deep-equal');
const pLimit = require('p-limit');
const Mustache = require('mustache');
/**
* ensure that Mustache does not escape any characters
*
* @param {string} text -
* @returns {string} text
*/
Mustache.escape = function (text) {
return text;
};
/**
* MetadataType class that gets extended by their specific metadata type class.
* Provides default functionality that can be overwritten by child metadata type classes
*
*/
class MetadataType {
/**
* Returns file contents mapped to their filename without '.json' ending
*
* @param {string} dir directory that contains '.json' files to be read
* @param {boolean} [listBadKeys] do not print errors, used for badKeys()
* @returns {TYPE.MetadataTypeMap} fileName => fileContent map
*/
static getJsonFromFS(dir, listBadKeys) {
const fileName2FileContent = {};
try {
const files = File.readdirSync(dir);
for (const fileName of files) {
try {
if (fileName.endsWith('.json')) {
const fileContent = File.readJSONFile(dir, fileName, true, false);
const fileNameWithoutEnding = File.reverseFilterIllegalFilenames(
fileName.split(/\.(\w|-)+-meta.json/)[0]
);
// We always store the filename using the External Key (CustomerKey or key) to avoid duplicate names.
// to ensure any changes are done to both the filename and external key do a check here
// ! convert numbers to string to allow numeric keys to be checked properly
const key = Number.isInteger(fileContent[this.definition.keyField])
? fileContent[this.definition.keyField].toString()
: fileContent[this.definition.keyField];
if (key === fileNameWithoutEnding || listBadKeys) {
fileName2FileContent[fileNameWithoutEnding] = fileContent;
} else {
Util.logger.error(
` ${this.definition.type} ${key}: Name of the metadata file and the JSON-key (${this.definition.keyField}) must match` +
Util.getGrayMsg(` - ${dir}/${fileName}`)
);
}
}
} catch (ex) {
// by catching this in the loop we gracefully handle the issue and move on to the next file
Util.metadataLogger('debug', this.definition.type, 'getJsonFromFS', ex);
}
}
} catch (ex) {
// this will catch issues with readdirSync
Util.metadataLogger('debug', this.definition.type, 'getJsonFromFS', ex);
throw new Error(ex);
}
return fileName2FileContent;
}
/**
* Returns fieldnames of Metadata Type. 'this.definition.fields' variable only set in child classes.
*
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {boolean} [isCaching] if true, then check if field should be skipped for caching
* @returns {string[]} Fieldnames
*/
static getFieldNamesToRetrieve(additionalFields, isCaching) {
const fieldNames = [];
for (const fieldName in this.definition.fields) {
if (
additionalFields?.includes(fieldName) ||
(this.definition.fields[fieldName].retrieving &&
!(isCaching && this.definition.fields[fieldName].skipCache))
) {
fieldNames.push(fieldName);
}
}
if (!fieldNames.includes(this.definition.idField)) {
// Always retrieve the ID because it may be used in references
fieldNames.push(this.definition.idField);
}
return fieldNames;
}
/**
* Deploys metadata
*
* @param {TYPE.MetadataTypeMap} metadata metadata mapped by their keyField
* @param {string} deployDir directory where deploy metadata are saved
* @param {string} retrieveDir directory where metadata after deploy should be saved
* @returns {Promise.<TYPE.MetadataTypeMap>} Promise of keyField => metadata map
*/
static async deploy(metadata, deployDir, retrieveDir) {
const upsertResults = await this.upsert(metadata, deployDir);
const savedMetadata = await this.saveResults(upsertResults, retrieveDir, null);
if (
this.properties.metaDataTypes.documentOnRetrieve.includes(this.definition.type) &&
!this.definition.documentInOneFile
) {
// * do not await here as this might take a while and has no impact on the deploy
// * this should only be run if documentation is on a per metadata record level. Types that document an overview into a single file will need a full retrieve to work instead
this.document(savedMetadata, true);
}
return upsertResults;
}
/**
* Gets executed after deployment of metadata type
*
* @param {TYPE.MetadataTypeMap} upsertResults metadata mapped by their keyField as returned by update/create
* @param {TYPE.MetadataTypeMap} originalMetadata metadata to be updated (contains additioanl fields)
* @param {{created: number, updated: number}} createdUpdated counter representing successful creates/updates
* @returns {void}
*/
static postDeployTasks(upsertResults, originalMetadata, createdUpdated) {}
/**
* helper for {@link MetadataType.createREST}
*
* @param {TYPE.MetadataTypeItem} metadataEntry a single metadata Entry
* @param {object} apiResponse varies depending on the API call
* @returns {void}
*/
static postCreateTasks(metadataEntry, apiResponse) {}
/**
* helper for {@link MetadataType.updateREST}
*
* @param {TYPE.MetadataTypeItem} metadataEntry a single metadata Entry
* @param {object} apiResponse varies depending on the API call
* @returns {void}
*/
static postUpdateTasks(metadataEntry, apiResponse) {}
/**
* helper for {@link MetadataType.createREST} when legacy API endpoints as these do not return the created item but only their new id
*
* @param {TYPE.MetadataTypeItem} metadataEntry a single metadata Entry
* @param {object} apiResponse varies depending on the API call
* @returns {Promise.<void>} -
*/
static async postDeployTasks_legacyApi(metadataEntry, apiResponse) {
if (!apiResponse?.[this.definition.idField] && !metadataEntry?.[this.definition.idField]) {
return;
}
const id =
apiResponse?.[this.definition.idField] || metadataEntry?.[this.definition.idField];
// re-retrieve created items because the API does not return any info for them except the new id (api key)
try {
const { metadata } = await this.retrieveForCache(null, null, 'id:' + id);
const item = Object.values(metadata)[0];
// ensure the "created item" cli log entry has the new auto-generated value
metadataEntry[this.definition.keyField] = item[this.definition.keyField];
// ensure postRetrieveTasks has the complete object in "apiResponse"
Object.assign(apiResponse, item);
// postRetrieveTasks will be run automatically on this via super.saveResult
} catch (ex) {
throw new Error(
`Could not get details for new ${this.definition.type} ${id} from server (${ex.message})`
);
}
}
/**
* Gets executed after retreive of metadata type
*
* @param {TYPE.MetadataTypeItem} metadata a single item
* @param {string} targetDir folder where retrieves should be saved
* @param {boolean} [isTemplating] signals that we are retrieving templates
* @returns {TYPE.MetadataTypeItem} cloned metadata
*/
static postRetrieveTasks(metadata, targetDir, isTemplating) {
return JSON.parse(JSON.stringify(metadata));
}
/**
* generic script that retrieves the folder path from cache and updates the given metadata with it after retrieve
*
* @param {TYPE.MetadataTypeItem} metadata a single item
*/
static setFolderPath(metadata) {
if (!this.definition.folderIdField) {
return;
}
try {
metadata.r__folder_Path = cache.searchForField(
'folder',
metadata[this.definition.folderIdField],
'ID',
'Path'
);
delete metadata[this.definition.folderIdField];
} catch (ex) {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}): Could not find folder (${ex.message})`
);
}
}
/**
* generic script that retrieves the folder ID from cache and updates the given metadata with it before deploy
*
* @param {TYPE.MetadataTypeItem} metadata a single item
*/
static setFolderId(metadata) {
if (!this.definition.folderIdField) {
return;
}
metadata[this.definition.folderIdField] = cache.searchForField(
'folder',
metadata.r__folder_Path,
'Path',
'ID'
);
delete metadata.r__folder_Path;
}
/**
* Gets metadata from Marketing Cloud
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {string[]} [subTypeArr] optionally limit to a single subtype
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<TYPE.MetadataTypeMapObj>} metadata
*/
static retrieve(retrieveDir, additionalFields, subTypeArr, key) {
Util.metadataLogger('error', this.definition.type, 'retrieve', `Not Supported`);
const metadata = {};
return { metadata: null, type: this.definition.type };
}
/**
* Gets metadata from Marketing Cloud
*
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {string[]} [subTypeArr] optionally limit to a single subtype
* @returns {Promise.<TYPE.MetadataTypeMapObj>} metadata
*/
static retrieveChangelog(additionalFields, subTypeArr) {
return this.retrieveForCache(additionalFields, subTypeArr);
}
/**
* Gets metadata cache with limited fields and does not store value to disk
*
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @param {string[]} [subTypeArr] optionally limit to a single subtype
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<TYPE.MetadataTypeMapObj>} metadata
*/
static async retrieveForCache(additionalFields, subTypeArr, key) {
return this.retrieve(null, additionalFields, subTypeArr, key);
}
/**
* Gets metadata cache with limited fields and does not store value to disk
*
* @param {string} templateDir Directory where retrieved metadata directory will be saved
* @param {string} name name of the metadata file
* @param {TYPE.TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} [subType] optionally limit to a single subtype
* @returns {Promise.<TYPE.MetadataTypeItemObj>} metadata
*/
static retrieveAsTemplate(templateDir, name, templateVariables, subType) {
Util.logger.error('retrieveAsTemplate is not supported yet for ' + this.definition.type);
Util.metadataLogger(
'debug',
this.definition.type,
'retrieveAsTemplate',
`(${templateDir}, ${name}, ${templateVariables}) no templating function`
);
return { metadata: null, type: this.definition.type };
}
/**
* Retrieve a specific Script by Name
*
* @param {string} templateDir Directory where retrieved metadata directory will be saved
* @param {string} uri rest endpoint for GET
* @param {TYPE.TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} name name (not key) of the metadata item
* @returns {Promise.<{metadata: TYPE.MetadataTypeItem, type: string}>} Promise
*/
static async retrieveTemplateREST(templateDir, uri, templateVariables, name) {
return this.retrieveREST(templateDir, uri, templateVariables, name);
}
/**
* Gets metadata cache with limited fields and does not store value to disk
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {string} templateDir (List of) Directory where built definitions will be saved
* @param {string} key name of the metadata file
* @param {TYPE.TemplateMap} templateVariables variables to be replaced in the metadata
* @returns {Promise.<TYPE.MetadataTypeItemObj>} single metadata
*/
static async buildTemplate(retrieveDir, templateDir, key, templateVariables) {
// retrieve metadata template
let metadataStr;
const typeDirArr = [this.definition.type];
const subType = await this.findSubType(retrieveDir, key);
if (subType) {
typeDirArr.push(subType);
}
const suffix = subType ? `-${subType}-meta` : '-meta';
const fileName = key + '.' + this.definition.type + suffix;
try {
// ! do not load via readJSONFile to ensure we get a string, not parsed JSON
// templated files might contain illegal json before the conversion back to the file that shall be saved
metadataStr = await File.readFilteredFilename(
[retrieveDir, ...typeDirArr],
fileName,
'json'
);
} catch (ex) {
try {
metadataStr = await this.readSecondaryFolder(
retrieveDir,
typeDirArr,
key,
fileName,
ex
);
} catch {
throw new Error(
`${this.definition.type}:: Could not find ./${File.normalizePath([
retrieveDir,
...typeDirArr,
fileName + '.json',
])}.`
);
}
// return;
}
if (this.definition.stringifyFieldsBeforeTemplate) {
// numeric fields are returned as numbers by the SDK/API. If we try to replace them in buildTemplate it would break the JSON format - but not if we stringify them first because then the {{{var}}} is in quotes
metadataStr = JSON.parse(metadataStr);
for (const field of this.definition.stringifyFieldsBeforeTemplate) {
if (metadataStr[field]) {
if (Array.isArray(metadataStr[field])) {
for (let i = 0; i < metadataStr[field].length; i++) {
metadataStr[field][i] = metadataStr[field][i].toString();
}
} else if ('object' === typeof metadataStr[field]) {
for (const subField in metadataStr[field]) {
metadataStr[field][subField] = metadataStr[field][subField].toString();
}
} else {
metadataStr[field] = metadataStr[field].toString();
}
}
}
metadataStr = JSON.stringify(metadataStr);
}
const metadata = JSON.parse(Util.replaceByObject(metadataStr, templateVariables));
this.keepTemplateFields(metadata);
// handle extracted code
// templating to extracted content is applied inside of buildTemplateForNested()
await this.buildTemplateForNested(
retrieveDir,
templateDir,
metadata,
templateVariables,
key
);
try {
// write to file
await File.writeJSONToFile([templateDir, ...typeDirArr], fileName, metadata);
Util.logger.info(
`- templated ${this.definition.type}: ${key} (${
metadata[this.definition.nameField]
})`
);
return { metadata: metadata, type: this.definition.type };
} catch (ex) {
throw new Error(`${this.definition.type}:: ${ex.message}`);
}
}
/**
* Gets executed before deploying metadata
*
* @param {TYPE.MetadataTypeItem} metadata a single metadata item
* @param {string} deployDir folder where files for deployment are stored
* @returns {Promise.<TYPE.MetadataTypeItem>} Promise of a single metadata item
*/
static async preDeployTasks(metadata, deployDir) {
return metadata;
}
/**
* Abstract create method that needs to be implemented in child metadata type
*
* @param {TYPE.MetadataTypeItem} metadata single metadata entry
* @param {string} deployDir directory where deploy metadata are saved
* @returns {void}
*/
static create(metadata, deployDir) {
Util.logger.error(
` ☇ skipping ${this.definition.type} ${metadata[this.definition.keyField]} / ${
metadata[this.definition.nameField]
}: create is not supported yet for ${this.definition.type}`
);
return;
}
/**
* Abstract update method that needs to be implemented in child metadata type
*
* @param {TYPE.MetadataTypeItem} metadata single metadata entry
* @param {TYPE.MetadataTypeItem} [metadataBefore] metadata mapped by their keyField
* @returns {void}
*/
static update(metadata, metadataBefore) {
Util.logger.error(
` ☇ skipping ${this.definition.type} ${metadata[this.definition.keyField]} / ${
metadata[this.definition.nameField]
}: update is not supported yet for ${this.definition.type}`
);
return;
}
/**
* Abstract refresh method that needs to be implemented in child metadata type
*
* @returns {void}
*/
static refresh() {
Util.logger.error(
` ☇ skipping ${this.definition.type}: refresh is not supported yet for ${this.definition.type}`
);
return;
}
/**
* Abstract execute method that needs to be implemented in child metadata type
*
* @returns {void}
*/
static execute() {
Util.logger.error(
` ☇ skipping ${this.definition.type}: execute is not supported yet for ${this.definition.type}`
);
return [];
}
/**
* Abstract pause method that needs to be implemented in child metadata type
*
* @returns {void}
*/
static pause() {
Util.logger.error(
` ☇ skipping ${this.definition.type}: pause is not supported yet for ${this.definition.type}`
);
return [];
}
/**
* test if metadata was actually changed or not to potentially skip it during deployment
*
* @param {TYPE.MetadataTypeItem} cachedVersion cached version from the server
* @param {TYPE.MetadataTypeItem} metadata item to upload
* @param {string} [fieldName] optional field name to use for identifying the record in logs
* @returns {boolean} true if metadata was changed
*/
static hasChanged(cachedVersion, metadata, fieldName) {
// should be set up type by type but the *_generic version is likely a good start for many types
return true;
}
/**
* test if metadata was actually changed or not to potentially skip it during deployment
*
* @param {TYPE.MetadataTypeItem} cachedVersion cached version from the server
* @param {TYPE.MetadataTypeItem} metadata item to upload
* @param {string} [fieldName] optional field name to use for identifying the record in logs
* @param {boolean} [silent] optionally suppress logging
* @returns {boolean} true on first identified deviation or false if none are found
*/
static hasChangedGeneric(cachedVersion, metadata, fieldName, silent) {
if (!cachedVersion) {
return true;
}
// we do need the full set in other places and hence need to work with a clone here
const clonedMetada = JSON.parse(JSON.stringify(metadata));
this.removeNotUpdateableFields(clonedMetada);
// iterate over what we want to upload rather than what we cached to avoid false positives
for (const prop in clonedMetada) {
if (this.definition.ignoreFieldsForUpdateCheck?.includes(prop)) {
continue;
}
if (
clonedMetada[prop] === null ||
['string', 'number', 'boolean'].includes(typeof clonedMetada[prop])
) {
// check simple variables directly
// check should ignore types to bypass string/number auto-conversions caused by SFMC-SDK
if (clonedMetada[prop] != cachedVersion[prop]) {
Util.logger.debug(
`${this.definition.type}:: ${
clonedMetada[fieldName || this.definition.keyField]
}.${prop} changed: '${cachedVersion[prop]}' to '${clonedMetada[prop]}'`
);
return true;
}
} else if (deepEqual(clonedMetada[prop], cachedVersion[prop])) {
// test complex objects here
Util.logger.debug(
`${this.definition.type}:: ${
clonedMetada[fieldName || this.definition.keyField]
}.${prop} changed: '${cachedVersion[prop]}' to '${clonedMetada[prop]}'`
);
return true;
}
}
if (!silent) {
Util.logger.verbose(
` ☇ skipping ${this.definition.type} ${clonedMetada[this.definition.keyField]} / ${
clonedMetada[fieldName || this.definition.nameField]
}: no change detected`
);
}
return false;
}
/**
* MetadataType upsert, after retrieving from target and comparing to check if create or update operation is needed.
*
* @param {TYPE.MetadataTypeMap} metadataMap metadata mapped by their keyField
* @param {string} deployDir directory where deploy metadata are saved
* @returns {Promise.<TYPE.MetadataTypeMap>} keyField => metadata map
*/
static async upsert(metadataMap, deployDir) {
const orignalMetadataMap = JSON.parse(JSON.stringify(metadataMap));
const metadataToUpdate = [];
const metadataToCreate = [];
let filteredByPreDeploy = 0;
for (const metadataKey in metadataMap) {
let hasError = false;
try {
// preDeployTasks parsing
let deployableMetadata;
try {
deployableMetadata = await this.preDeployTasks(
metadataMap[metadataKey],
deployDir
);
} catch (ex) {
// do this in case something went wrong during pre-deploy steps to ensure the total counter is correct
hasError = true;
deployableMetadata = metadataMap[metadataKey];
Util.logger.error(
` ☇ skipping ${this.definition.type} ${
deployableMetadata[this.definition.keyField]
} / ${deployableMetadata[this.definition.nameField]}: ${ex.message}`
);
}
// if preDeploy returns nothing then it cannot be deployed so skip deployment
if (deployableMetadata) {
metadataMap[metadataKey] = deployableMetadata;
// create normalizedKey off of whats in the json rather than from "metadataKey" because preDeployTasks might have altered something (type asset)
await this.createOrUpdate(
metadataMap,
metadataKey,
hasError,
metadataToUpdate,
metadataToCreate
);
} else {
filteredByPreDeploy++;
}
} catch (ex) {
Util.logger.errorStack(
ex,
`Upserting ${this.definition.type} failed: ${ex.message}`
);
}
}
const createLimit = pLimit(10);
const createResults = (
await Promise.all(
metadataToCreate
.filter((r) => r !== undefined && r !== null)
.map((metadataEntry) =>
createLimit(() => this.create(metadataEntry, deployDir))
)
)
).filter((r) => r !== undefined && r !== null);
const updateLimit = pLimit(10);
const updateResults = (
await Promise.all(
metadataToUpdate
.filter((r) => r !== undefined && r !== null)
.map((metadataEntry) =>
updateLimit(() => this.update(metadataEntry.after, metadataEntry.before))
)
)
).filter((r) => r !== undefined && r !== null);
// Logging
Util.logger.info(
`${this.definition.type} upsert: ${createResults.length} of ${metadataToCreate.length} created / ${updateResults.length} of ${metadataToUpdate.length} updated` +
(filteredByPreDeploy > 0 ? ` / ${filteredByPreDeploy} filtered` : '')
);
let upsertResults;
if (this.definition.bodyIteratorField === 'Results') {
// if Results then parse as SOAP
// put in Retrieve Format for parsing
// todo add handling when response does not contain items.
// @ts-ignore
const metadataResults = createResults
.concat(updateResults)
// TODO remove Object.keys check after create/update SOAP methods stop returning empty objects instead of null
.filter((r) => r !== undefined && r !== null && Object.keys(r).length !== 0)
.flatMap((r) => r.Results)
.map((r) => r.Object);
upsertResults = this.parseResponseBody({ Results: metadataResults });
} else {
// likely comming from one of the many REST APIs
// put in Retrieve Format for parsing
// todo add handling when response does not contain items.
// @ts-ignore
const metadataResults = createResults.concat(updateResults).filter(Boolean);
upsertResults = this.parseResponseBody(metadataResults);
}
await this.postDeployTasks(upsertResults, orignalMetadataMap, {
created: createResults.length,
updated: updateResults.length,
});
return upsertResults;
}
/**
* helper for {@link MetadataType.upsert}
*
* @param {TYPE.MetadataTypeMap} metadataMap list of metadata
* @param {string} metadataKey key of item we are looking at
* @param {boolean} hasError error flag from previous code
* @param {TYPE.MetadataTypeItemDiff[]} metadataToUpdate list of items to update
* @param {TYPE.MetadataTypeItem[]} metadataToCreate list of items to create
* @returns {'create' | 'update' | 'skip'} action to take
*/
static createOrUpdate(metadataMap, metadataKey, hasError, metadataToUpdate, metadataToCreate) {
const normalizedKey = File.reverseFilterIllegalFilenames(
metadataMap[metadataKey][this.definition.keyField]
);
// Update if it already exists; Create it if not
const maxKeyLength = this.definition.maxKeyLength || 36;
if (
Util.logger.level === 'debug' &&
metadataMap[metadataKey][this.definition.idField] &&
this.definition.idField !== this.definition.keyField
) {
// TODO: re-evaluate in future releases if & when we managed to solve folder dependencies once and for all
// only used if resource is excluded from cache and we still want to update it
// needed e.g. to rewire lost folders
Util.logger.warn(
' - Hotfix for non-cachable resource found in deploy folder. Trying update:'
);
Util.logger.warn(JSON.stringify(metadataMap[metadataKey]));
if (hasError) {
metadataToUpdate.push(null);
return 'skip';
} else {
metadataToUpdate.push({
before: {},
after: metadataMap[metadataKey],
});
return 'update';
}
} else if (cache.getByKey(this.definition.type, normalizedKey)) {
// normal way of processing update files
const cachedVersion = cache.getByKey(this.definition.type, normalizedKey);
if (!this.hasChanged(cachedVersion, metadataMap[metadataKey])) {
hasError = true;
}
if (Util.OPTIONS.changeKeyField) {
if (this.definition.keyField == this.definition.idField) {
Util.logger.error(
` - --changeKeyField cannot be used for types that use their ID as key. Skipping change.`
);
hasError = true;
} else if (this.definition.keyIsFixed) {
Util.logger.error(
` - type ${this.definition.type} does not support --changeKeyField and --changeKeyValue. Skipping change.`
);
hasError = true;
} else if (!metadataMap[metadataKey][Util.OPTIONS.changeKeyField]) {
Util.logger.error(
` - --changeKeyField is set to ${Util.OPTIONS.changeKeyField} but no value was found in the metadata. Skipping change.`
);
hasError = true;
} else if (Util.OPTIONS.changeKeyField === this.definition.keyField) {
// simple issue, used WARN to avoid signaling a problem to ci/cd and don't fail deploy
Util.logger.warn(
` - --changeKeyField is set to the same value as the keyField for ${this.definition.type}. Skipping change.`
);
} else if (metadataMap[metadataKey][Util.OPTIONS.changeKeyField]) {
// NOTE: trim twice while getting the newKey value to remove leading spaces before limiting the length
const newKey = (metadataMap[metadataKey][Util.OPTIONS.changeKeyField] + '')
.trim()
.slice(0, maxKeyLength)
.trim();
if (metadataMap[metadataKey][Util.OPTIONS.changeKeyField] + '' > maxKeyLength) {
Util.logger.warn(
`${this.definition.type} ${this.definition.keyField} may not exceed ${maxKeyLength} characters. Truncated the value in field ${Util.OPTIONS.changeKeyField} to ${newKey}`
);
}
if (metadataKey == newKey) {
Util.logger.warn(
` - --changeKeyField(${Util.OPTIONS.changeKeyField}) is providing the current value of the key (${metadataKey}). Skipping change.`
);
} else {
Util.logger.info(
` - Changing ${this.definition.type} key from ${metadataKey} to ${newKey} via --changeKeyField=${Util.OPTIONS.changeKeyField}`
);
metadataMap[metadataKey][this.definition.keyField] = newKey;
// ensure we can delete the old file(s) after the successful update
Util.changedKeysMap[this.definition.type] ||= {};
Util.changedKeysMap[this.definition.type][newKey] = metadataKey;
}
}
} else if (Util.OPTIONS.changeKeyValue) {
// NOTE: trim twice while getting the newKey value to remove leading spaces before limiting the length
const newKey = Util.OPTIONS.changeKeyValue.trim().slice(0, maxKeyLength).trim();
if (Util.OPTIONS.changeKeyValue.trim().length > maxKeyLength) {
Util.logger.warn(
`${this.definition.type} ${this.definition.keyField} may not exceed ${maxKeyLength} characters. Truncated your value to ${newKey}`
);
}
if (this.definition.keyField == this.definition.idField) {
Util.logger.error(
` - --changeKeyValue cannot be used for types that use their ID as key. Skipping change.`
);
hasError = true;
} else if (this.definition.keyIsFixed) {
Util.logger.error(
` - type ${this.definition.type} does not support --changeKeyField and --changeKeyValue. Skipping change.`
);
hasError = true;
} else if (metadataKey == newKey) {
Util.logger.warn(
` - --changeKeyValue is providing the current value of the key (${metadataKey}). Skipping change.`
);
} else {
Util.logger.info(
` - Changing ${this.definition.type} key from ${metadataKey} to ${newKey} via --changeKeyValue`
);
metadataMap[metadataKey][this.definition.keyField] = newKey;
// ensure we can delete the old file(s) after the successful update
Util.changedKeysMap[this.definition.type] ||= {};
Util.changedKeysMap[this.definition.type][newKey] = metadataKey;
}
}
if (hasError) {
// do this in case something went wrong during pre-deploy steps to ensure the total counter is correct
metadataToUpdate.push(null);
return 'skip';
} else {
// add ObjectId to allow actual update
metadataMap[metadataKey][this.definition.idField] =
cachedVersion[this.definition.idField];
metadataToUpdate.push({
before: cachedVersion,
after: metadataMap[metadataKey],
});
return 'update';
}
} else {
if (hasError) {
// do this in case something went wrong during pre-deploy steps to ensure the total counter is correct
metadataToCreate.push(null);
return 'skip';
} else {
metadataToCreate.push(metadataMap[metadataKey]);
return 'create';
}
}
}
/**
* Creates a single metadata entry via REST
*
* @param {TYPE.MetadataTypeItem} metadataEntry a single metadata Entry
* @param {string} uri rest endpoint for POST
* @returns {Promise.<object> | null} Promise of API response or null in case of an error
*/
static async createREST(metadataEntry, uri) {
this.removeNotCreateableFields(metadataEntry);
try {
// set to empty object in case API returned nothing to be able to update it in helper classes
const response = (await this.client.rest.post(uri, metadataEntry)) || {};
await this.postCreateTasks(metadataEntry, response);
Util.logger.info(
` - created ${this.definition.type}: ${
metadataEntry[this.definition.keyField] ||
metadataEntry[this.definition.nameField]
} / ${metadataEntry[this.definition.nameField]}`
);
return response;
} catch (ex) {
const parsedErrors = this.getErrorsREST(ex);
Util.logger.error(
` ☇ error creating ${this.definition.type} ${
metadataEntry[this.definition.keyField] ||
metadataEntry[this.definition.nameField]
} / ${metadataEntry[this.definition.nameField]}:`
);
if (parsedErrors.length) {
for (const msg of parsedErrors) {
Util.logger.error(' • ' + msg);
}
} else if (ex?.message) {
Util.logger.debug(ex.message);
}
return null;
}
}
/**
* Creates a single metadata entry via fuel-soap (generic lib not wrapper)
*
* @param {TYPE.MetadataTypeItem} metadataEntry single metadata entry
* @param {boolean} [handleOutside] if the API reponse is irregular this allows you to handle it outside of this generic method
* @returns {Promise.<object> | null} Promise of API response or null in case of an error
*/
static async createSOAP(metadataEntry, handleOutside) {
const soapType = this.definition.soapType || this.definition.type;
this.removeNotCreateableFields(metadataEntry);
try {
const response = await this.client.soap.create(
Util.capitalizeFirstLetter(soapType),
metadataEntry,
null
);
if (!handleOutside) {
Util.logger.info(
` - created ${this.definition.type}: ${
metadataEntry[this.definition.keyField]
} / ${metadataEntry[this.definition.nameField]}`
);
}
return response;
} catch (ex) {
this._handleSOAPErrors(ex, 'creating', metadataEntry, handleOutside);
return null;
}
}
/**
* Updates a single metadata entry via REST
*
* @param {TYPE.MetadataTypeItem} metadataEntry a single metadata Entry
* @param {string} uri rest endpoint for PATCH
* @param {'patch'|'post'|'put'} [httpMethod] defaults to 'patch'; some update requests require PUT instead of PATCH
* @returns {Promise.<object> | null} Promise of API response or null in case of an error
*/
static async updateREST(metadataEntry, uri, httpMethod = 'patch') {
this.removeNotUpdateableFields(metadataEntry);
try {
// set to empty object in case API returned nothing to be able to update it in helper classes
const response = (await this.client.rest[httpMethod](uri, metadataEntry)) || {};
await this._postChangeKeyTasks(metadataEntry);
this.getErrorsREST(response);
await this.postUpdateTasks(metadataEntry, response);
// some times, e.g. automation dont return a key in their update response and hence we need to fall back to name
Util.logger.info(
` - updated ${this.definition.type}: ${
metadataEntry[this.definition.keyField] ||
metadataEntry[this.definition.nameField]
} / ${metadataEntry[this.definition.nameField]}`
);
return response;
} catch (ex) {
const parsedErrors = this.getErrorsREST(ex);
Util.logger.error(
` ☇ error updating ${this.definition.type} ${
metadataEntry[this.definition.keyField] ||
metadataEntry[this.definition.nameField]
} / ${metadataEntry[this.definition.nameField]}:`
);
for (const msg of parsedErrors) {
Util.logger.error(' • ' + msg);
}
return null;
}
}
/**
* helper for {@link MetadataType.updateREST} and {@link MetadataType.updateSOAP} that removes old files after the key was changed
*
* @private
* @param {TYPE.MetadataTypeItem} metadataEntry a single metadata Entry
* @param {boolean} [keepMap] some types require to check the old-key new-key relationship in their postDeployTasks; currently used by dataExtension only
* @returns {void}
*/
static async _postChangeKeyTasks(metadataEntry, keepMap = false) {
if (
(Util.OPTIONS.changeKeyField || Util.OPTIONS.changeKeyValue) &&
Util.changedKeysMap?.[this.definition.type]?.[metadataEntry[this.definition.keyField]]
) {
const oldKey =
Util.changedKeysMap?.[this.definition.type]?.[
metadataEntry[this.definition.keyField]
];
// delete file(s) of old key
await this.postDeleteTasks(oldKey);
// fix key in cache
const typeCache = cache.getCache()[this.definition.type];
typeCache[metadataEntry[this.definition.keyField]] = typeCache[oldKey];
delete typeCache[oldKey];
if (!keepMap) {
// clean entry from to-do list
delete Util.changedKeysMap?.[this.definition.type]?.[
metadataEntry[this.definition.keyField]
];
}
}
}
/**
* Updates a single metadata entry via fuel-soap (generic lib not wrapper)
*
* @param {TYPE.MetadataTypeItem} metadataEntry single metadata entry
* @param {boolean} [handleOutside] if the API reponse is irregular this allows you to handle it outside of this generic method
* @returns {Promise.<object> | null} Promise of API response or null in case of an error
*/
static async updateSOAP(metadataEntry, handleOutside) {
const soapType = this.definition.soapType || this.definition.type;
this.removeNotUpdateableFields(metadataEntry);
try {
const response = await this.client.soap.update(
Util.capitalizeFirstLetter(soapType),
metadataEntry,
null
);
if (!handleOutside) {
Util.logger.info(
` - updated ${this.definition.type}: ${
metadataEntry[this.definition.keyField]
} / ${metadataEntry[this.definition.nameField]}`
);
}
await this._postChangeKeyTasks(metadataEntry);
return response;
} catch (ex) {
this._handleSOAPErrors(ex, 'updating', metadataEntry, handleOutside);
return null;
}
}
/**
*
* @param {Error} ex error that occured
* @param {'creating'|'updating'} msg what to print in the log
* @param {TYPE.MetadataTypeItem} [metadataEntry] single metadata entry
* @param {boolean} [handleOutside] if the API reponse is irregular this allows you to handle it outside of this generic method
*/
static _handleSOAPErrors(ex, msg, metadataEntry, handleOutside) {
if (handleOutside) {
throw ex;
} else {
const errorMsg = this.getSOAPErrorMsg(ex);
const name = metadataEntry ? ` '${metadataEntry[this.definition.keyField]}'` : '';
Util.logger.error(` ☇ error ${msg} ${this.definition.type}${name}: ${errorMsg}`);
}
}
/**
* helper for {@link MetadataType._handleSOAPErrors}
*
* @param {Error} ex error that occured
* @returns {string} error message
*/
static getSOAPErrorMsg(ex) {
if (ex?.json?.Results?.length) {