-
Notifications
You must be signed in to change notification settings - Fork 36
/
MobileKeyword.js
555 lines (525 loc) · 21.1 KB
/
MobileKeyword.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
'use strict';
import TYPE from '../../types/mcdev.d.js';
import MetadataType from './MetadataType.js';
import { Util } from '../util/util.js';
import File from '../util/file.js';
import cache from '../util/cache.js';
/**
* MobileKeyword MetadataType
*
* @augments MetadataType
*/
class MobileKeyword extends MetadataType {
/**
* Retrieves Metadata of Mobile Keywords
* Endpoint /legacy/v1/beta/mobile/keyword/ return all Mobile Keywords with all details.
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {void} [_] unused parameter
* @param {void} [__] unused parameter
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<TYPE.MetadataTypeMapObj> | void} Promise of metadata
*/
static retrieve(retrieveDir, _, __, key) {
try {
let queryParams;
[key, queryParams] = this.#getRetrieveKeyAndUrl(key);
return super.retrieveREST(
retrieveDir,
'/legacy/v1/beta/mobile/keyword/' + queryParams,
null,
key
);
} catch (ex) {
// if the mobileMessage does not exist, the API returns the error "Request failed with status code 400 (ERR_BAD_REQUEST)" which would otherwise bring execution to a hold
if (key && ex.code === 'ERR_BAD_REQUEST') {
Util.logger.info(
`Downloaded: ${this.definition.type} (0)${Util.getKeysString(key)}`
);
} else {
throw ex;
}
}
}
/**
* Builds map of metadata entries mapped to their keyfields
*
* @param {object} body json of response body
* @param {string|number} [singleRetrieve] key of single item to filter by
* @returns {TYPE.MetadataTypeMap} keyField => metadata map
*/
static parseResponseBody(body, singleRetrieve) {
const bodyIteratorField = this.definition.bodyIteratorField;
const keyField = this.definition.keyField;
const metadataStructure = {};
if (body !== null) {
if (Array.isArray(body)) {
// in some cases data is just an array
for (const item of body) {
this.#createCustomKeyField(item);
const key = item[keyField];
metadataStructure[key] = item;
}
} else if (body[bodyIteratorField]) {
for (const item of body[bodyIteratorField]) {
this.#createCustomKeyField(item);
const key = item[keyField];
metadataStructure[key] = item;
}
} else if (singleRetrieve) {
// some types will return a single item intead of an array if the key is supported by their api
this.#createCustomKeyField(body);
// ! currently, the id: prefix is only supported by journey (interaction)
if (singleRetrieve.startsWith('id:')) {
singleRetrieve = body[keyField];
}
metadataStructure[singleRetrieve] = body;
return metadataStructure;
}
if (
metadataStructure[singleRetrieve] &&
(typeof singleRetrieve === 'string' || typeof singleRetrieve === 'number')
) {
// in case we really just wanted one entry but couldnt do so in the api call, filter it here
const single = {};
single[singleRetrieve] = metadataStructure[singleRetrieve];
return single;
} else if (singleRetrieve) {
return {};
}
}
return metadataStructure;
}
/**
* helper for {@link MobileKeyword.parseResponseBody} that creates a custom key field for this type based on mobileCode and keyword
*
* @private
* @param {TYPE.MetadataType} metadata single item
*/
static #createCustomKeyField(metadata) {
metadata.c__codeKeyword = metadata.code.code + '.' + metadata.keyword;
}
/**
* helper for {@link MobileKeyword.preDeployTasks} and {@link MobileKeyword.createOrUpdate} to ensure we have code & keyword properly set
*
* @private
* @param {TYPE.MetadataType} metadata single item
*/
static #setCodeAndKeyword(metadata) {
const [code, keyword] = metadata.c__codeKeyword.split('.');
// mobileCode
metadata.code = {
id: cache.searchForField('mobileCode', code, 'code', 'id'),
};
// keyword
metadata.keyword = keyword;
}
/**
* 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 createOrUpdateAction = super.createOrUpdate(
metadataMap,
metadataKey,
hasError,
metadataToUpdate,
metadataToCreate
);
if (createOrUpdateAction === 'update') {
// in case --changeKeyField or --changeKeyValue was used, let's ensure we set code & keyword here again
this.#setCodeAndKeyword(metadataMap[metadataKey]);
}
return createOrUpdateAction;
}
/**
* Retrieves event definition metadata for caching
*
* @param {void} _ parameter not used
* @param {void} __ parameter not used
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<TYPE.MetadataTypeMapObj>} Promise of metadata
*/
static retrieveForCache(_, __, key) {
return this.retrieve(null, null, null, key);
}
/**
* retrieve an item and create a template from it
*
* @param {string} templateDir Directory where retrieved metadata directory 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>} Promise of metadata
*/
static async retrieveAsTemplate(templateDir, key, templateVariables) {
try {
let queryParams;
[key, queryParams] = this.#getRetrieveKeyAndUrl(key);
return super.retrieveTemplateREST(
templateDir,
`/legacy/v1/beta/mobile/keyword/` + queryParams,
templateVariables,
key
);
} catch (ex) {
// if the mobileMessage does not exist, the API returns the error "Request failed with status code 400 (ERR_BAD_REQUEST)" which would otherwise bring execution to a hold
if (key && ex.code === 'ERR_BAD_REQUEST') {
Util.logger.info(
`Downloaded: ${this.definition.type} (0)${Util.getKeysString(key)}`
);
} else {
throw ex;
}
}
}
/**
* helper for {@link MobileKeyword.retrieve} and {@link MobileKeyword.retrieveAsTemplate}
*
* @private
* @param {string} key customer key of single item to retrieve / name of the metadata file
* @returns {Array} key, queryParams
*/
static #getRetrieveKeyAndUrl(key) {
let queryParams;
if (key) {
if (key.startsWith('id:')) {
// overwrite queryParams
queryParams = key.slice(3);
} else if (key.includes('.')) {
// keywords are always uppercased
key = key.toUpperCase();
// format: code.keyword
const [code, keyword] = key.split('.');
queryParams = `?view=simple&$where=keyword%20eq%20%27${keyword}%27%20and%code%20eq%20%27${code}%27%20`;
} else {
throw new Error(
`key ${key} has unexpected format. Expected 'code.keyword' or 'id:yourId'`
);
}
} else {
queryParams = '?view=simple';
}
return [key, queryParams];
}
/**
* Creates a single item
*
* @param {TYPE.MetadataTypeItem} metadata a single item
* @returns {Promise} Promise
*/
static create(metadata) {
return super.createREST(metadata, '/legacy/v1/beta/mobile/keyword/');
}
/**
* Updates a single item
*
* @param {TYPE.MetadataTypeItem} metadata a single item
* @returns {Promise} Promise
*/
static update(metadata) {
return super.updateREST(
metadata,
'/legacy/v1/beta/mobile/keyword/' + metadata[this.definition.idField],
'post' // upsert API, post for insert and update!
);
}
/**
* manages post retrieve steps
*
* @param {TYPE.MetadataTypeItem} metadata a single item
* @returns {TYPE.CodeExtractItem | TYPE.MetadataTypeItem | void} Array with one metadata object and one ssjs string; or single metadata object; nothing if filtered
*/
static postRetrieveTasks(metadata) {
try {
cache.searchForField('mobileCode', metadata.code.code, 'code', 'id');
} catch {
// in case the the mobileCode cannot be found, do not save this keyword as its no longer accessible in the UI either
Util.logger.debug(
` - skipping ${this.definition.type} ${
metadata[this.definition.keyField]
}. Could not find parent mobileCode ${metadata.code.code}`
);
return;
}
if (metadata.responseMessage) {
// extract message body
const codeArr = [];
// keep between tags
const { fileExt, code } = this.prepExtractedCode(metadata.responseMessage);
delete metadata.responseMessage;
codeArr.push({
subFolder: null,
fileName: metadata[this.definition.keyField],
fileExt: fileExt,
content: code,
});
return { json: metadata, codeArr: codeArr, subFolder: null };
} else {
return metadata;
}
}
/**
* helper for {@link MobileKeyword.postRetrieveTasks} and {@link MobileKeyword._buildForNested}
*
* @param {string} metadataScript the code of the file
* @returns {{fileExt:string,code:string}} returns found extension and file content
*/
static prepExtractedCode(metadataScript) {
const code = metadataScript;
const fileExt = 'amp';
return { fileExt, code };
}
/**
* helper for {@link MetadataType.buildDefinition}
* handles extracted code if any are found for complex types
*
* @param {string} templateDir Directory where metadata templates are stored
* @param {string|string[]} targetDir (List of) Directory where built definitions will be saved
* @param {TYPE.MetadataTypeItem} metadata main JSON file that was read from file system
* @param {TYPE.TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} templateName name of the template to be built
* @returns {Promise.<string[][]>} list of extracted files with path-parts provided as an array
*/
static buildDefinitionForNested(
templateDir,
targetDir,
metadata,
templateVariables,
templateName
) {
return this._buildForNested(
templateDir,
targetDir,
metadata,
templateVariables,
templateName,
'definition'
);
}
/**
* helper for {@link MetadataType.buildTemplate}
* handles extracted code if any are found for complex types
*
* @example scripts are saved as 1 json and 1 ssjs file. both files need to be run through templating
* @param {string} templateDir Directory where metadata templates are stored
* @param {string|string[]} targetDir (List of) Directory where built definitions will be saved
* @param {TYPE.MetadataTypeItem} metadata main JSON file that was read from file system
* @param {TYPE.TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} templateName name of the template to be built
* @returns {Promise.<string[][]>} list of extracted files with path-parts provided as an array
*/
static buildTemplateForNested(
templateDir,
targetDir,
metadata,
templateVariables,
templateName
) {
return this._buildForNested(
templateDir,
targetDir,
metadata,
templateVariables,
templateName,
'template'
);
}
/**
* helper for {@link MobileKeyword.buildTemplateForNested} / {@link MobileKeyword.buildDefinitionForNested}
* handles extracted code if any are found for complex types
*
* @param {string} templateDir Directory where metadata templates are stored
* @param {string|string[]} targetDir (List of) Directory where built definitions will be saved
* @param {TYPE.MetadataTypeItem} metadata main JSON file that was read from file system
* @param {TYPE.TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} templateName name of the template to be built
* @param {'definition'|'template'} mode defines what we use this helper for
* @returns {Promise.<string[][]>} list of extracted files with path-parts provided as an array
*/
static async _buildForNested(
templateDir,
targetDir,
metadata,
templateVariables,
templateName,
mode
) {
// get code from filesystem
let code = await this._mergeCode(metadata, templateDir, templateName);
if (!code) {
return null;
}
const file = this.prepExtractedCode(code, metadata.name);
const fileExt = file.fileExt;
code = file.code;
// apply templating
try {
if (mode === 'definition') {
// replace template variables with their values
code = this.applyTemplateValues(code, templateVariables);
} else if (mode === 'template') {
// replace template values with corresponding variable names
code = this.applyTemplateNames(code, templateVariables);
}
} catch {
throw new Error(
`${this.definition.type}:: Error applying template variables on ${
templateName + '.' + this.definition.type
}-meta.${fileExt}.`
);
}
// write to file
const targetDirArr = Array.isArray(targetDir) ? targetDir : [targetDir];
const nestedFilePaths = [];
// keep old name if creating templates, otherwise use new name
const fileName = mode === 'definition' ? metadata[this.definition.keyField] : templateName;
for (const targetDir of targetDirArr) {
File.writeToFile(
[targetDir, this.definition.type],
fileName + '.' + this.definition.type + '-meta',
fileExt,
code
);
nestedFilePaths.push([
targetDir,
this.definition.type,
fileName + '.' + this.definition.type + '-meta.' + fileExt,
]);
}
return nestedFilePaths;
}
/**
* prepares an event definition for deployment
*
* @param {TYPE.MetadataTypeItem} metadata a single MobileKeyword
* @param {string} deployDir directory of deploy files
* @returns {Promise.<TYPE.MetadataTypeItem>} Promise
*/
static async preDeployTasks(metadata, deployDir) {
// code
metadata.responseMessage = await this._mergeCode(metadata, deployDir);
if (metadata.responseMessage && metadata.keywordType === 'NORMAL') {
throw new Error(
`Custom Response Text is not supported for keywords of type 'NORMAL'. Please remove the .amp file or change the keywordType to 'STOP' or 'INFO'.`
);
}
if (!metadata.companyName && metadata.keywordType !== 'NORMAL') {
metadata.companyName = 'IGNORED';
Util.logger.debug(
` - No companyName found for keyword ${
metadata[this.definition.keyField]
}. Setting to IGNORED.`
);
}
this.#setCodeAndKeyword(metadata);
return metadata;
}
/**
* 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 async postCreateTasks(metadataEntry, apiResponse) {
await super.postDeployTasks_legacyApi(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 async postUpdateTasks(metadataEntry, apiResponse) {
await super.postDeployTasks_legacyApi(metadataEntry, apiResponse);
}
/**
* helper for {@link MobileKeyword.preDeployTasks} that loads extracted code content back into JSON
*
* @param {TYPE.MetadataTypeItem} metadata a single definition
* @param {string} deployDir directory of deploy files
* @param {string} [templateName] name of the template used to built defintion (prior applying templating)
* @returns {Promise.<string>} content for metadata.script
*/
static async _mergeCode(metadata, deployDir, templateName) {
templateName ||= metadata[this.definition.keyField];
const codePath = File.normalizePath([
deployDir,
this.definition.type,
templateName + '.' + this.definition.type + '-meta',
]);
if (await File.pathExists(codePath + '.amp')) {
return await File.readFilteredFilename(
[deployDir, this.definition.type],
templateName + '.' + this.definition.type + '-meta',
'amp'
);
} else {
// keeep this as a debug message, as it is optional and hence not an error
Util.logger.debug(`Could not find ${codePath}.amp`);
return null;
}
}
/**
* Delete a metadata item from the specified business unit
*
* @param {string} key Identifier of item
* @returns {Promise.<boolean>} deletion success status
*/
static async deleteByKey(key) {
// get id from cache
const { metadata } = await this.retrieveForCache(undefined, undefined, key);
if (!metadata[key]) {
Util.logger.error(`Could not find ${this.definition.type} with key ${key}.`);
return false;
}
const id = metadata[key][this.definition.idField];
// execute delete
Util.logger.info(
' - Note: As long as the provided API key once existed, you will not see an error even if the mobileKeyword is already deleted.'
);
return super.deleteByKeyREST('/legacy/v1/beta/mobile/keyword/' + id, key, false);
}
/**
* clean up after deleting a metadata item
*
* @param {string} customerKey Identifier of metadata item
* @returns {void}
*/
static async postDeleteTasks(customerKey) {
// delete local copy: retrieve/cred/bu/type/...-meta.json
// delete local copy: retrieve/cred/bu/type/...-meta.amp
super.postDeleteTasks(customerKey, [`${this.definition.type}-meta.amp`]);
}
/**
* should return only the json for all but asset, query and script that are saved as multiple files
* additionally, the documentation for dataExtension and automation should be returned
*
* @param {string[]} keyArr customerkey of the metadata
* @returns {string[]} list of all files that need to be committed in a flat array ['path/file1.ext', 'path/file2.ext']
*/
static getFilesToCommit(keyArr) {
const path = File.normalizePath([
this.properties.directories.retrieve,
this.buObject.credential,
this.buObject.businessUnit,
this.definition.type,
]);
const fileList = keyArr.flatMap((key) => [
File.normalizePath([path, `${key}.${this.definition.type}-meta.json`]),
File.normalizePath([path, `${key}.${this.definition.type}-meta.amp`]),
]);
return fileList;
}
}
// Assign definition to static attributes
import MetadataTypeDefinitions from '../MetadataTypeDefinitions.js';
MobileKeyword.definition = MetadataTypeDefinitions.mobileKeyword;
export default MobileKeyword;