-
Notifications
You must be signed in to change notification settings - Fork 34
/
DataExtension.js
1120 lines (1056 loc) · 46.8 KB
/
DataExtension.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';
const jsonToTable = require('json-to-table');
const TYPE = require('../../types/mcdev.d');
const MetadataType = require('./MetadataType');
const DataExtensionField = require('./DataExtensionField');
const Folder = require('./Folder');
const Util = require('../util/util');
const File = require('../util/file');
const auth = require('../util/auth');
const cache = require('../util/cache');
const pLimit = require('p-limit');
/**
* DataExtension MetadataType
*
* @augments MetadataType
*/
class DataExtension extends MetadataType {
/**
* Upserts dataExtensions after retrieving them from source and target to compare
* if create or update operation is needed.
*
* @param {TYPE.DataExtensionMap} metadataMap dataExtensions mapped by their customerKey
* @returns {Promise} Promise
*/
static async upsert(metadataMap) {
// get existing DE-fields for DE-keys in deployment package to properly handle add/update/delete of fields
const fieldOptions = {};
for (const key of Object.keys(metadataMap)) {
fieldOptions.filter = fieldOptions.filter
? {
leftOperand: {
leftOperand: 'DataExtension.CustomerKey',
operator: 'equals',
rightOperand: key,
},
operator: 'OR',
rightOperand: fieldOptions.filter,
}
: {
leftOperand: 'DataExtension.CustomerKey',
operator: 'equals',
rightOperand: key,
};
}
Util.logger.info(` - Caching dependent Metadata: dataExtensionField`);
await this._attachFields(metadataMap, fieldOptions);
/** @type {object[]} */
const metadataToCreate = [];
/** @type {object[]} */
const metadataToUpdate = [];
let filteredByPreDeploy = 0;
for (const metadataKey in metadataMap) {
try {
metadataMap[metadataKey] = await this.preDeployTasks(metadataMap[metadataKey]);
} catch (ex) {
// output error & remove from deploy list
Util.logger.error(
` ☇ skipping ${this.definition.type} ${
metadataMap[this.definition.keyField]
} / ${metadataMap[this.definition.nameField]}: ${ex.message}`
);
delete metadataMap[metadataKey];
// skip rest of handling for this DE
filteredByPreDeploy++;
continue;
}
await this.createOrUpdate(
metadataMap,
metadataKey,
false,
metadataToUpdate,
metadataToCreate
);
}
if (metadataToUpdate.length) {
Util.logger.info(
' - Please note that Data Retention Policies can only be set during creation, not during update.'
);
}
const createLimit = pLimit(10);
const createResults = (
await Promise.allSettled(
metadataToCreate
.filter((r) => r !== undefined && r !== null)
.map((metadataEntry) => createLimit(() => this.create(metadataEntry)))
)
)
.filter((r) => r !== undefined && r !== null)
.filter(this.#filterUpsertResults);
const updateLimit = pLimit(10);
const updateResults = (
await Promise.allSettled(
metadataToUpdate
.filter((r) => r !== undefined && r !== null)
.map((metadataEntry) =>
updateLimit(() => this.update(metadataEntry.after, metadataEntry.before))
)
)
)
.filter((r) => r !== undefined && r !== null)
.filter(this.#filterUpsertResults);
const successfulResults = [...createResults, ...updateResults];
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 (successfulResults.length > 0) {
const metadataResults = successfulResults
.map((r) => r.value.Results[0].Object)
.map((r) => {
// if only one fields added will return object otherwise array
if (Array.isArray(r?.Fields?.Field)) {
r.Fields = r.Fields.Field;
} else if (r?.Fields?.Field) {
r.Fields = [r.Fields.Field];
}
return r;
});
upsertResults = super.parseResponseBody({ Results: metadataResults });
} else {
upsertResults = {};
}
await this.postDeployTasks(upsertResults, metadataMap, {
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 async createOrUpdate(
metadataMap,
metadataKey,
hasError,
metadataToUpdate,
metadataToCreate
) {
const action = await super.createOrUpdate(
metadataMap,
metadataKey,
hasError,
metadataToUpdate,
metadataToCreate
);
if (action === 'update') {
// Update dataExtension + Columns if they already exist; Create them if not
// Modify columns for update call
DataExtensionField.client = this.client;
DataExtensionField.properties = this.properties;
DataExtension.oldFields ||= {};
DataExtension.oldFields[metadataMap[metadataKey][this.definition.keyField]] =
await DataExtensionField.prepareDeployColumnsOnUpdate(
metadataMap[metadataKey].Fields,
metadataKey
);
if (
metadataMap[metadataKey][this.definition.keyField] !== metadataKey &&
metadataMap[metadataKey].Fields.length
) {
// changeKeyValue / changeKeyField used
Util.logger.warn(
` - ${this.definition.type} ${metadataKey}: Cannot change fields while updating the key. Skipping field update in favor of key update.`
);
metadataMap[metadataKey].Fields.length = 0;
}
// convert simple array into object.Array.object format to cope with how the XML body in the SOAP call needs to look like:
// <Fields>
// <Field>
// <CustomerKey>SubscriberKey</CustomerKey>
// ..
// </Field>
// </Fields>
metadataMap[metadataKey].Fields = { Field: metadataMap[metadataKey].Fields };
} else if (action === 'create') {
this.#cleanupRetentionPolicyFields(metadataMap[metadataKey]);
// convert simple array into object.Array.object format to cope with how the XML body in the SOAP call needs to look like:
// <Fields>
// <Field>
// <CustomerKey>SubscriberKey</CustomerKey>
// ..
// </Field>
// </Fields>
metadataMap[metadataKey].Fields = { Field: metadataMap[metadataKey].Fields };
}
}
/**
* helper for {@link upsert}
*
* @private
* @param {object} res -
* @returns {boolean} true: keep, false: discard
*/
static #filterUpsertResults(res) {
if (res.status === 'rejected') {
// promise rejects, whole request failed
Util.logger.error('- error upserting dataExtension: ' + res.reason);
return false;
} else if (res.value == undefined || Object.keys(res.value).length === 0) {
// in case of returning empty result handle gracefully
// TODO: consider if SOAP handler for this should really return empty object
return false;
} else if (res.value.results) {
Util.logger.error(
'- error upserting dataExtension: ' +
(res.value.Results[0].Object ? res.value.Results[0].Object.Name : '') +
'. ' +
res.value.Results[0].StatusMessage
);
return false;
} else if (res.status === 'fulfilled' && res?.value?.faultstring) {
// can happen that the promise does not reject, but that it resolves an error
Util.logger.error('- error upserting dataExtension: ' + res.value.faultstring);
return false;
} else {
return true;
}
}
/**
* Create a single dataExtension. Also creates their columns in 'dataExtension.columns'
*
* @param {TYPE.DataExtensionItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static async create(metadata) {
return super.createSOAP(metadata);
}
/**
* SFMC saves a date in "RetainUntil" under certain circumstances even
* if that field duplicates whats in the period fields
* during deployment, that extra value is not accepted by the APIs which is why it needs to be removed
*
* @private
* @param {TYPE.DataExtensionItem} metadata single metadata entry
* @returns {void}
*/
static #cleanupRetentionPolicyFields(metadata) {
if (
metadata.DataRetentionPeriodLength &&
metadata.DataRetentionPeriodUnitOfMeasure &&
metadata.RetainUntil !== ''
) {
metadata.RetainUntil = '';
Util.logger.warn(
` - RetainUntil date was reset automatically because RetentionPeriod info was found in: ${metadata.CustomerKey}`
);
}
}
/**
* Updates a single dataExtension. Also updates their columns in 'dataExtension.columns'
*
* @param {TYPE.DataExtensionItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static async update(metadata) {
return super.updateSOAP(metadata);
}
/**
* Gets executed after deployment of metadata type
*
* @param {TYPE.DataExtensionMap} upsertedMetadata metadata mapped by their keyField
* @param {TYPE.DataExtensionMap} originalMetadata metadata to be updated (contains additioanl fields)
* @param {{created: number, updated: number}} createdUpdated counter representing successful creates/updates
* @returns {void}
*/
static postDeployTasks(upsertedMetadata, originalMetadata, createdUpdated) {
for (const key in upsertedMetadata) {
const item = upsertedMetadata[key];
const oldKey = Util.changedKeysMap?.[this.definition.type]?.[key] || key;
delete Util.changedKeysMap?.[this.definition.type]?.[key];
const cachedVersion = createdUpdated.updated
? cache.getByKey(this.definition.type, oldKey)
: null;
if (cachedVersion) {
// UPDATE
// restore retention values that are typically not returned by the update call
item.RowBasedRetention = cachedVersion.RowBasedRetention;
item.ResetRetentionPeriodOnImport = cachedVersion.ResetRetentionPeriodOnImport;
item.DeleteAtEndOfRetentionPeriod = cachedVersion.DeleteAtEndOfRetentionPeriod;
item.RetainUntil = cachedVersion.RetainUntil;
const existingFields = DataExtension.oldFields[item[this.definition.keyField]];
if (item.Fields === '') {
// if no fields were updated, we need to set Fields to "empty string" for the API to work
// reset here to get the correct field list
item.Fields = Object.keys(existingFields)
.map((el) => existingFields[el])
.sort((a, b) => a.Ordinal - b.Ordinal);
} else if (existingFields) {
// get list of updated fields
/** @type {TYPE.DataExtensionFieldItem[]} */
const updatedFieldsArr = originalMetadata[oldKey].Fields.Field.filter(
(field) => field.ObjectID && field.ObjectID !== ''
);
// convert existing fields obj into array and sort
/** @type {TYPE.DataExtensionFieldItem[]} */
const finalFieldsArr = Object.keys(existingFields)
.map((el) => {
/** @type {TYPE.DataExtensionFieldItem} */
const existingField = existingFields[el];
// check if the current field was updated and then override with it. otherwise use existing value
const field =
updatedFieldsArr.find(
(field) => field.ObjectID === existingField.ObjectID
) || existingField;
// field does not have a ordinal value because we rely on array order
field.Ordinal = existingField.Ordinal;
// updating FieldType is not supported by API and hence removed
field.FieldType = existingField.FieldType;
return field;
})
.sort((a, b) => a.Ordinal - b.Ordinal);
// get list of new fields
/** @type {TYPE.DataExtensionFieldItem[]} */
const newFieldsArr = originalMetadata[oldKey].Fields.Field.filter(
(field) => !field.ObjectID
);
// push new fields to end of list
if (newFieldsArr.length) {
finalFieldsArr.push(...newFieldsArr);
}
// sort Fields entry to the end of the object for saving in .json
delete item.Fields;
item.Fields = finalFieldsArr;
}
}
// UPDATE + CREATE
for (const field of item.Fields) {
DataExtensionField.postRetrieveTasks(field, true);
}
}
}
/**
* Retrieves dataExtension metadata. Afterwards starts retrieval of dataExtensionColumn metadata retrieval
*
* @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 {void} [_] unused parameter
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<{metadata: TYPE.DataExtensionMap, type: string}>} Promise of item map
*/
static async retrieve(retrieveDir, additionalFields, _, key) {
/** @type {TYPE.SoapRequestParams} */
let requestParams = null;
/** @type {TYPE.SoapRequestParams} */
let fieldOptions = null;
if (key) {
requestParams = {
filter: {
leftOperand: 'CustomerKey',
operator: 'equals',
rightOperand: key,
},
};
fieldOptions = {
filter: {
leftOperand: 'DataExtension.CustomerKey',
operator: 'equals',
rightOperand: key,
},
};
}
let metadata = await this._retrieveAll(additionalFields, requestParams);
// in case of cache dont get fields
if (metadata && retrieveDir) {
// get fields from API
await this._attachFields(metadata, fieldOptions, additionalFields);
}
if (!retrieveDir && this.buObject.eid !== this.buObject.mid) {
// for caching, we want to retrieve shared DEs as well from the instance parent BU
Util.logger.info(
' - Caching dependent Metadata: dataExtension (shared via _ParentBU_)'
);
/** @type {TYPE.BuObject} */
const buObjectParentBu = {
eid: this.properties.credentials[this.buObject.credential].eid,
mid: this.properties.credentials[this.buObject.credential].eid,
businessUnit: Util.parentBuName,
credential: this.buObject.credential,
};
try {
this.client = auth.getSDK(buObjectParentBu);
} catch (ex) {
Util.logger.error(ex.message);
return;
}
const metadataParentBu = await this._retrieveAll(additionalFields);
// get shared folders to match our shared / synched Data Extensions
const subTypeArr = this.definition.dependencies
.filter((item) => item.startsWith('folder-'))
.map((item) => item.slice(7));
Util.logger.info(' - Caching dependent Metadata: folder (shared via _ParentBU_)');
Util.logSubtypes(subTypeArr);
Folder.client = this.client;
Folder.buObject = buObjectParentBu;
Folder.properties = this.properties;
const result = await Folder.retrieveForCache(null, subTypeArr);
cache.mergeMetadata('folder', result.metadata, this.buObject.eid);
// get the types and clean out non-shared ones
const folderTypesFromParent = require('../MetadataTypeDefinitions').folder
.folderTypesFromParent;
for (const metadataEntry in metadataParentBu) {
try {
// get the data extension type from the folder
const folderContentType = cache.searchForField(
'folder',
metadataParentBu[metadataEntry].CategoryID,
'ID',
'ContentType',
this.buObject.eid
);
if (!folderTypesFromParent.includes(folderContentType)) {
Util.logger.verbose(
`removing ${metadataEntry} because r__folder_ContentType '${folderContentType}' identifies this DE as not being shared`
);
delete metadataParentBu[metadataEntry];
}
} catch (ex) {
Util.logger.debug(
`removing ${metadataEntry} because of error while retrieving r__folder_ContentType: ${ex.message}`
);
delete metadataParentBu[metadataEntry];
}
}
// revert client to current default
this.client = auth.getSDK(this.buObject);
Folder.client = auth.getSDK(this.buObject);
// make sure to overwrite parent bu DEs with local ones
metadata = { ...metadataParentBu, ...metadata };
}
if (retrieveDir) {
const savedMetadata = await super.saveResults(metadata, retrieveDir, null);
Util.logger.info(
`Downloaded: ${this.definition.type} (${Object.keys(savedMetadata).length})` +
Util.getKeysString(key)
);
if (this.properties.metaDataTypes.documentOnRetrieve.includes(this.definition.type)) {
await this.document(savedMetadata);
}
}
return { metadata: metadata, type: 'dataExtension' };
}
/**
* helper to retrieve all dataExtension fields and attach them to the dataExtension metadata
*
* @private
* @param {TYPE.DataExtensionMap} metadata already cached dataExtension metadata
* @param {TYPE.SoapRequestParams} [fieldOptions] optionally filter results
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @returns {Promise.<void>} -
*/
static async _attachFields(metadata, fieldOptions, additionalFields) {
const fieldsObj = await this._retrieveFields(fieldOptions, additionalFields);
const fieldKeys = Object.keys(fieldsObj);
// add fields to corresponding DE
for (const key of fieldKeys) {
const field = fieldsObj[key];
if (metadata[field?.DataExtension?.CustomerKey]) {
metadata[field.DataExtension.CustomerKey].Fields.push(field);
} else {
Util.logger.warn(` - Issue retrieving data extension fields. key='${key}'`);
}
}
// sort fields by Ordinal value (API returns field unsorted)
for (const metadataEntry in metadata) {
metadata[metadataEntry].Fields.sort(DataExtensionField.sortDeFields);
}
// remove attributes that we do not want to retrieve
// * do this after sorting on the DE's field list
for (const key of fieldKeys) {
DataExtensionField.postRetrieveTasks(fieldsObj[key], true);
}
}
/**
* Retrieves dataExtension metadata. Afterwards starts retrieval of dataExtensionColumn metadata retrieval
*
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @returns {Promise.<{metadata: TYPE.DataExtensionMap, type: string}>} Promise of item map
*/
static async retrieveChangelog(additionalFields) {
const metadata = await this._retrieveAll(additionalFields);
return { metadata: metadata, type: 'dataExtension' };
}
/**
* manages post retrieve steps
*
* @param {TYPE.DataExtensionItem} metadata a single dataExtension
* @returns {TYPE.DataExtensionItem} metadata
*/
static async postRetrieveTasks(metadata) {
// Error during deploy if SendableSubscriberField.Name = '_SubscriberKey' even though it is retrieved like that
// Therefore map it to 'Subscriber Key'. Retrieving afterward still results in '_SubscriberKey'
if (metadata.SendableSubscriberField?.Name === '_SubscriberKey') {
metadata.SendableSubscriberField.Name = 'Subscriber Key';
}
this.setFolderPath(metadata);
// DataExtensionTemplate
if (metadata.Template?.CustomerKey) {
try {
metadata.r__dataExtensionTemplate_Name = cache.searchForField(
'dataExtensionTemplate',
metadata.Template.CustomerKey,
'CustomerKey',
'Name'
);
delete metadata.Template;
} catch (ex) {
Util.logger.debug(ex.message);
// Let's allow retrieving such DEs but warn that they cannot be deployed to another BU.
// Deploying to same BU still works!
// A workaround exists but it's likely not beneficial to explain to users:
// Create a DE based on the not-supported template on the target BU, retrieve it, copy the Template.CustomerKey into the to-be-deployed DE (or use mcdev-templating), done
Util.logger.warn(
` - Issue with dataExtension '${
metadata[this.definition.nameField]
}': Could not find specified DataExtension Template. Please note that DataExtensions based on SMSMessageTracking and SMSSubscriptionLog cannot be deployed automatically across BUs at this point.`
);
}
}
// remove the date fields manually here because we need them in the changelog but not in the saved json
delete metadata.CreatedDate;
delete metadata.ModifiedDate;
return metadata;
}
/**
* Helper to retrieve Data Extension Fields
*
* @private
* @param {TYPE.SoapRequestParams} [options] options (e.g. continueRequest)
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @returns {Promise.<TYPE.DataExtensionFieldMap>} Promise of items
*/
static async _retrieveFields(options, additionalFields) {
if (!options) {
// dont print this during updates or templating which retrieves fields DE-by-DE
Util.logger.info(' - Caching dependent Metadata: dataExtensionField');
}
DataExtensionField.client = this.client;
DataExtensionField.properties = this.properties;
const response = await DataExtensionField.retrieveForCache(options, additionalFields);
return response.metadata;
}
/**
* helps retrieving fields during templating and deploy where we dont want the full list
*
* @private
* @param {TYPE.DataExtensionMap} metadata list of DEs
* @param {string} customerKey external key of single DE
* @returns {Promise.<void>} -
*/
static async _retrieveFieldsForSingleDe(metadata, customerKey) {
const fieldOptions = {
filter: {
leftOperand: 'DataExtension.CustomerKey',
operator: 'equals',
rightOperand: customerKey,
},
};
const fieldsObj = await this._retrieveFields(fieldOptions);
DataExtensionField.client = this.client;
DataExtensionField.properties = this.properties;
const fieldArr = DataExtensionField.convertToSortedArray(fieldsObj);
// remove attributes that we do not want to retrieve
// * do this after sorting on the DE's field list
for (const field of fieldArr) {
DataExtensionField.postRetrieveTasks(field, true);
}
metadata[customerKey].Fields = fieldArr;
}
/**
* helper for {@link super.updateREST} and {@link super.updateSOAP} that removes old files after the key was changed
*
* @private
* @param {TYPE.MetadataTypeItem} metadataEntry a single metadata Entry
* @returns {void}
*/
static async _postChangeKeyTasks(metadataEntry) {
super._postChangeKeyTasks(metadataEntry, true);
}
/**
* prepares a DataExtension for deployment
*
* @param {TYPE.DataExtensionItem} metadata a single data Extension
* @returns {Promise.<TYPE.DataExtensionItem>} Promise of updated single DE
*/
static async preDeployTasks(metadata) {
if (metadata.Name.startsWith('_')) {
throw new Error(`Cannot Upsert Strongly Typed Data Extensions`);
}
if (
this.buObject.eid !== this.buObject.mid &&
metadata.r__folder_Path.startsWith('Shared Items')
) {
throw new Error(`Cannot Create/Update a Shared Data Extension from the Child BU`);
}
if (metadata.r__folder_Path.startsWith('Synchronized Data Extensions')) {
throw new Error(
`Cannot Create/Update a Synchronized Data Extension. Please use Contact Builder to maintain these`
);
}
// folder
super.setFolderId(metadata);
// DataExtensionTemplate
if (metadata.r__dataExtensionTemplate_Name) {
// remove templated fields
for (const templateField of this.definition.templateFields[
metadata.r__dataExtensionTemplate_Name
]) {
for (let index = 0; index < metadata.Fields.length; index++) {
const element = metadata.Fields[index];
if (element.Name === templateField) {
metadata.Fields.splice(index, 1);
Util.logger.debug(`Removed template field: ${templateField}`);
break;
}
}
}
// get template's CustomerKey
try {
metadata.Template = {
CustomerKey: cache.searchForField(
'dataExtensionTemplate',
metadata.r__dataExtensionTemplate_Name,
'Name',
'CustomerKey'
),
};
delete metadata.r__dataExtensionTemplate_Name;
} catch (ex) {
Util.logger.debug(ex.message);
// It is assumed that non-supported types would not have been converted to r__dataExtensionTemplate_Name upon retrieve.
// Deploying to same BU therefore still works!
// A workaround for cross-BU deploy exists but it's likely not beneficial to explain to users:
// Create a DE based on the not-supported template on the target BU, retrieve it, copy the Template.CustomerKey into the to-be-deployed DE (or use mcdev-templating), done
throw new Error(
`Could not find specified DataExtension Template. Please note that DataExtensions based on SMSMessageTracking and SMSSubscriptionLog cannot be deployed automatically across BUs at this point.`
);
}
}
// contenttype
delete metadata.r__folder_ContentType;
// Error if SendableSubscriberField.Name = '_SubscriberKey' even though it is retrieved like that
// Therefore map it to 'Subscriber Key'. Retrieving afterward still results in '_SubscriberKey'
// TODO remove from preDeploy with release of version 4, keep until then to help with migration of old metadata
if (
metadata.SendableSubscriberField &&
metadata.SendableSubscriberField.Name === '_SubscriberKey'
) {
metadata.SendableSubscriberField.Name = 'Subscriber Key';
}
return metadata;
}
/**
* Saves json content to a html table in the local file system. Will create the parent directory if it does not exist.
* The json's first level of keys must represent the rows and the secend level the columns
*
* @private
* @param {TYPE.DataExtensionItem} json single dataextension
* @param {object[][]} tabled prepped array for output in tabular format
* @returns {string} file content
*/
static _generateDocHtml(json, tabled) {
let output =
'<html> <head> <style> html, table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tbody>tr:hover { background-color: #EBECF0; } </style> </head> <body></body>';
output += `<h2>${json.CustomerKey}</h2>`;
if (json.CustomerKey !== json.Name) {
output += `<p><b>Error - Name not equal to External Key:</b> ${json.Name}</p>`;
}
output += `<p><b>Description:</b> ${json.Description || 'n/a'}</p>`;
output += `<p><b>Folder:</b> ${
json.r__folder_Path ||
'<i>Hidden! Could not find folder with ID ' + json.CategoryID + '</i>'
}</p>`;
output += `<p><b>Fields in table:</b> ${tabled.length - 1}</p>`;
output += '<p><b>Sendable:</b> ';
output +=
json.IsSendable === true
? 'Yes (<i>' +
json.SendableDataExtensionField.Name +
'</i> to <i>' +
json.SendableSubscriberField.Name +
'</i>)</p>\n\n'
: `No</p>\n\n`;
output += `<p><b>Testable:</b> ${json.IsTestable === true ? 'Yes' : 'No'}</p>\n\n`;
if (json.r__dataExtensionTemplate_Name) {
output += `<p><b>Template:</b> ${json.r__dataExtensionTemplate_Name}</p>`;
}
output += '<table><thead><tr>';
for (const element of tabled[0]) {
output += '<th>' + element + '</th>';
}
output += '</tr><thead><tbody>';
for (let i = 1; i < tabled.length; i++) {
output += '<tr>';
for (const field of tabled[i]) {
output += `<td>${field}</td>`;
}
output += '</tr>';
}
output += '</tbody></table>';
return output;
}
/**
* Experimental: Only working for DataExtensions:
* Saves json content to a html table in the local file system. Will create the parent directory if it does not exist.
* The json's first level of keys must represent the rows and the secend level the columns
*
* @private
* @param {TYPE.DataExtensionItem} json dataextension
* @param {object[][]} tabled prepped array for output in tabular format
* @returns {string} file content
*/
static _generateDocMd(json, tabled) {
let output = `## ${json.CustomerKey}\n\n`;
if (json.CustomerKey !== json.Name) {
output += `**Name** (not equal to External Key)**:** ${json.Name}\n\n`;
}
output +=
`**Description:** ${json.Description || 'n/a'}\n\n` +
`**Folder:** ${
json.r__folder_Path ||
'_Hidden! Could not find folder with ID ' + json.CategoryID + '_'
}/\n\n` +
`**Fields in table:** ${tabled.length - 1}\n\n`;
output += '**Sendable:** ';
output +=
json.IsSendable === true
? 'Yes (`' +
json.SendableDataExtensionField.Name +
'` to `' +
json.SendableSubscriberField.Name +
'`)\n\n'
: `No\n\n`;
output += `**Testable:** ${json.IsTestable === true ? 'Yes' : 'No'}\n\n`;
if (json.r__dataExtensionTemplate_Name) {
output += `**Template:** ${json.r__dataExtensionTemplate_Name}\n\n`;
}
let tableSeparator = '';
for (const column of tabled[0]) {
output += `| ${column} `;
tableSeparator += '| --- ';
}
output += `|\n${tableSeparator}|\n`;
for (let i = 1; i < tabled.length; i++) {
for (const field of tabled[i]) {
output += `| ${field} `;
}
output += '|\n';
}
return output;
}
/**
* Saves json content to a html table in the local file system. Will create the parent directory if it does not exist.
* The json's first level of keys must represent the rows and the secend level the columns
*
* @private
* @param {string} directory directory the file will be written to
* @param {string} filename name of the file without '.json' ending
* @param {TYPE.DataExtensionItem} json dataextension.columns
* @param {'html'|'md'} mode html or md
* @param {string[]} [fieldsToKeep] list of keys(columns) to show. This will also specify
* @returns {Promise.<boolean>} Promise of success of saving the file
*/
static async _writeDoc(directory, filename, json, mode, fieldsToKeep) {
let fieldsJson = Object.values(json.Fields);
if (fieldsToKeep) {
const newJson = [];
for (const element of fieldsJson) {
const newJsonElement = {};
for (const field of fieldsToKeep) {
newJsonElement[field] = element[field];
}
newJson.push(newJsonElement);
}
fieldsJson = newJson;
}
const tabled = jsonToTable(fieldsJson);
let output;
if (mode === 'html') {
output = DataExtension._generateDocHtml(json, tabled);
} else if (mode === 'md') {
output = DataExtension._generateDocMd(json, tabled);
}
try {
// write to disk
await File.writeToFile(directory, filename + '.dataExtension-doc', mode, output);
} catch (ex) {
Util.logger.error(`DataExtension.writeDeToX(${mode}):: error | ` + ex.message);
}
}
/**
* Parses metadata into a readable Markdown/HTML format then saves it
*
* @param {TYPE.DataExtensionMap} [metadataMap] a list of dataExtension definitions
* @returns {Promise.<void>} -
*/
static async document(metadataMap) {
try {
if (!metadataMap) {
metadataMap = this.readBUMetadataForType(
File.normalizePath([
this.properties.directories.retrieve,
this.buObject.credential,
this.buObject.businessUnit,
]),
true
).dataExtension;
}
} catch (ex) {
Util.logger.error(ex.message);
return;
}
const docPath = File.normalizePath([
this.properties.directories.retrieve,
this.buObject.credential,
this.buObject.businessUnit,
this.definition.type,
]);
if (!metadataMap || !Object.keys(metadataMap).length) {
// as part of retrieve & manual execution we could face an empty folder
return;
}
const columnsToIterateThrough = ['IsNullable', 'IsPrimaryKey'];
const columnsToPrint = [
'Name',
'FieldType',
'MaxLength',
'IsPrimaryKey',
'IsNullable',
'DefaultValue',
];
return Promise.all(
Object.keys(metadataMap).map((key) => {
if (metadataMap[key]?.Fields?.length) {
for (const field of metadataMap[key].Fields) {
field.IsNullable = !Util.isTrue(field.IsRequired);
for (const prop of columnsToIterateThrough) {
if (Util.isTrue(field[prop])) {
field[prop] = '+';
} else if (Util.isFalse(field[prop])) {
field[prop] = '-';
}
}
}
if (['html', 'both'].includes(this.properties.options.documentType)) {
return this._writeDoc(
docPath + '/',
key,
metadataMap[key],
'html',
columnsToPrint
);
}
if (['md', 'both'].includes(this.properties.options.documentType)) {
return this._writeDoc(
docPath + '/',
key,
metadataMap[key],
'md',
columnsToPrint
);
}
}
})
);
}
/**
* Delete a metadata item from the specified business unit
*
* @param {string} customerKey Identifier of data extension
* @returns {Promise.<boolean>} deletion success status
*/
static deleteByKey(customerKey) {
return super.deleteByKeySOAP(customerKey);
}
/**
* clean up after deleting a metadata item
*
* @param {string} customerKey Identifier of metadata item
* @returns {Promise.<void>} - promise
*/
static async postDeleteTasks(customerKey) {
// delete local copy: retrieve/cred/bu/dataExtension/...-meta.json
// delete local copy: doc/dataExtension/cred/bu/...md
await super.postDeleteTasks(customerKey, [`${this.definition.type}-doc.md`]);
}
/**
* Retrieves folder metadata into local filesystem. Also creates a uniquePath attribute for each folder.
*
* @returns {Promise.<{metadata: TYPE.DataExtensionMap, type: string}>} Promise
*/
static async retrieveForCache() {
return this.retrieve(null, ['ObjectID', 'CustomerKey', 'Name'], this.buObject, null, null);
}
/**
* Retrieves dataExtension metadata in template format.
*
* @param {string} templateDir Directory where retrieved metadata directory will be saved
* @param {string} name name of the metadata item
* @param {TYPE.TemplateMap} templateVariables variables to be replaced in the metadata
* @returns {Promise.<{metadata: TYPE.DataExtensionMap, type: string}>} Promise of items
*/
static async retrieveAsTemplate(templateDir, name, templateVariables) {
const options = {
filter: {
leftOperand: 'Name',
operator: 'equals',
rightOperand: name,
},
};
const metadata = await this._retrieveAll(null, options);
if (!Object.keys(metadata).length) {
Util.logger.error(`${this.definition.type} '${name}' not found on server.`);
Util.logger.info('Downloaded: dataExtension (0)');
return { metadata: {}, type: 'dataExtension' };
}
const customerKey = Object.keys(metadata)[0];
await this._retrieveFieldsForSingleDe(metadata, customerKey);
for (const key in metadata) {
try {
// API returns field unsorted
metadata[key].Fields.sort((a, b) => a.Ordinal - b.Ordinal);
const originalKey = key;
const metadataCleaned = JSON.parse(
JSON.stringify(await this.postRetrieveTasks(metadata[key]))
);
this.keepTemplateFields(metadataCleaned);
const metadataTemplated = JSON.parse(
Util.replaceByObject(JSON.stringify(metadataCleaned), templateVariables)
);
await File.writeJSONToFile(
[templateDir, this.definition.type].join('/'),
originalKey + '.' + this.definition.type + '-meta',
metadataTemplated
);