forked from 4ossiblellc/dynamodb-update-expression
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
497 lines (443 loc) · 14.1 KB
/
index.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
/**
* Created by jazarja, 4ossiblellc on 9/20/16.
* Updated for ES6 & Efficiency by DashOS on 06/28/17
*/
import merge from "deepmerge";
import _ from "lodash";
function isEmpty(map) {
for (const key of Object.keys(map)) {
if (map[key]) {
return false;
}
}
return true;
}
const deepDiffMapper = (function() {
return {
VALUE_CREATED: "created",
VALUE_UPDATED: "updated",
VALUE_DELETED: "deleted",
VALUE_UNCHANGED: "unchanged",
map(obj1, obj2) {
if (this.isFunction(obj1) || this.isFunction(obj2)) {
throw "Invalid argument. Function given, object expected.";
}
if (this.isValue(obj1) || this.isValue(obj2)) {
return {
type: this.compareValues(obj1, obj2),
data: obj2,
dataType: obj1 === undefined ? typeof obj2 : typeof obj1
};
}
if (this.isArray(obj1) || this.isArray(obj2)) {
return {
type: this.compareValues(obj1, obj2),
data: obj2,
dataType: "list"
};
}
const diff = {};
let key;
for (key in obj1) {
if (this.isFunction(obj1[key])) {
continue;
}
let value2;
if (typeof obj2[key] !== "undefined") {
value2 = obj2[key];
}
diff[key] = this.map(obj1[key], value2);
}
for (key in obj2) {
if (this.isFunction(obj2[key]) || typeof diff[key] !== "undefined") {
continue;
}
diff[key] = this.map(undefined, obj2[key]);
}
return diff;
},
compareValues(value1, value2) {
if (value1 === value2) {
return this.VALUE_UNCHANGED;
}
if (typeof value1 === "undefined") {
return this.VALUE_CREATED;
}
if (typeof value2 === "undefined") {
return this.VALUE_DELETED;
}
return this.VALUE_UPDATED;
},
isFunction(obj) {
return {}.toString.apply(obj) === "[object Function]";
},
isArray(obj) {
return {}.toString.apply(obj) === "[object Array]";
},
isObject(obj) {
return {}.toString.apply(obj) === "[object Object]";
},
isValue(obj) {
return !this.isObject(obj) && !this.isArray(obj);
}
};
})();
const removeSpecialChars = function(s) {
return s
.replace(/\./g, "")
.replace(/:/g, "")
.replace(/#/g, "")
.replace(/-/g, "")
.replace(/_/g, "")
.replace(/;/g, "");
};
const updateExpressionGenerator = function(
compareResult,
options,
path,
excludeFields
) {
const request = {
UpdateExpression: "",
ExpressionAttributeNames: {},
ExpressionAttributeValues: {}
};
let setExpression = "";
let hasSetExpression = false;
let removeExpression = "";
let hasRemoveExpression = false;
var filterOutDeleteFields = function(obj, path) {
const wholeList = {
updateList: [],
removeList: []
};
let name;
for (const i in obj) {
// console.log(i + " = " + JSON.stringify(obj[i], null, 4) +
// ", hasOwnProperty: " + obj.hasOwnProperty(
// i));
// console.log("");
// if(Array.isArray(obj[i])) {
// obj[i].forEach(arrayRemoveFunc);
// } else
if (obj.hasOwnProperty(i) && typeof obj[i] === "object") {
if (
obj[i].type === "updated" &&
(obj[i].data === "" || obj[i].data === undefined)
) {
wholeList.removeList.push({
name: (path ? `${path}.` : "") + i
});
} else if (
(obj[i].type === "updated" || obj[i].type === "created") &&
obj[i].data !== undefined
) {
// console.log("pushed => " + obj[i].dataType, (path ? path + "." : "") + i + " = " + obj[i].data);
wholeList.updateList.push({
name: (path ? `${path}.` : "") + i,
value: obj[i].data,
dataType: obj[i].dataType
});
} else if (
(obj[i].type === undefined && obj[i].data === undefined) ||
(obj[i].type &&
obj[i].type !== "deleted" &&
obj[i].type !== "unchanged")
) {
const partial = isNaN(parseInt(i, 10)) ? `.${i}` : `[${i}]`;
name = path !== null ? path + partial : i;
// console.log("- nested object ->", name, obj[i].dataType);
const childList = filterOutDeleteFields(obj[i], name);
wholeList.updateList = wholeList.updateList.concat(
childList.updateList
);
wholeList.removeList = wholeList.removeList.concat(
childList.removeList
);
}
}
}
// console.log("returning updateList: " + updateList);
return wholeList;
};
const wholeList = filterOutDeleteFields(compareResult, null);
wholeList.updateList.forEach(expr => {
// change this logic to have # in front of .
const propName = expr.name
.replace(/&/g, "")
.replace(/_/g, "")
.replace(/\[/g, "")
.replace(/\]/g, "");
const splittedByDotPropName = expr.name.split(".");
const propNameExpressionName = `#${splittedByDotPropName
.map(removeSpecialChars)
.join(".#")}`;
splittedByDotPropName.forEach(partialName => {
request.ExpressionAttributeNames[
`#${removeSpecialChars(partialName)}`
] = partialName;
});
const propNameExpressionValue = `:${removeSpecialChars(propName)}`;
if (hasSetExpression) {
setExpression += `, ${propNameExpressionName} = ${propNameExpressionValue}`;
} else {
setExpression += `SET ${propNameExpressionName} = ${propNameExpressionValue}`;
hasSetExpression = true;
}
request.ExpressionAttributeValues[propNameExpressionValue] = expr.value;
});
wholeList.removeList.forEach((expr, index) => {
// var propName = expr.name.replace(/&/g, "").replace(/_/g, "").replace(
// /\[/g, "").replace(/\]/g, "");
const splittedByDotPropName = expr.name.split(".");
const propNameExpressionName = `#${splittedByDotPropName
.map(removeSpecialChars)
.join(".#")}`;
splittedByDotPropName.forEach(partialName => {
request.ExpressionAttributeNames[
`#${removeSpecialChars(partialName)}`
] = partialName;
});
if (hasRemoveExpression) {
removeExpression += `, ${propNameExpressionName}`;
} else {
removeExpression += `REMOVE ${propNameExpressionName}`;
hasRemoveExpression = true;
}
});
if (isEmpty(request.ExpressionAttributeNames)) {
delete request.ExpressionAttributeNames;
}
if (hasSetExpression && hasRemoveExpression) {
request.UpdateExpression = `${setExpression.trim()} ${removeExpression.trim()}`;
} else if (hasSetExpression) {
request.UpdateExpression = setExpression.trim();
} else if (hasRemoveExpression) {
request.UpdateExpression = removeExpression.trim();
}
return request;
};
const removeExpressionGenerator = function(
original,
removes,
compareResult,
path,
itemUniqueId
) {
const request = {
UpdateExpression: "",
ExpressionAttributeNames: {},
ExpressionAttributeValues: {}
};
let setExpression = "";
let hasSetExpression = false;
let removeExpression = "";
let hasRemoveExpression = false;
var filterOutCreateFields = function(obj, path) {
let updateList = [];
let name;
for (const i in obj) {
// console.log(i + " = " + JSON.stringify(obj[i], null, 4) +
// ", hasOwnProperty: " + obj.hasOwnProperty(
// i));
// console.log("");
// if(Array.isArray(obj[i])) {
// obj[i].forEach(arrayRemoveFunc);
// } else
if (obj.hasOwnProperty(i) && typeof obj[i] === "object") {
if (
(obj[i].type === "updated" || obj[i].type === "deleted") &&
obj[i].data
) {
// console.log("pushed => " + obj[i].dataType, (path ? path + "." : "") + i + " = " + obj[i].data);
updateList.push({
name: (path ? `${path}.` : "") + i,
value: obj[i].data,
dataType: obj[i].dataType
});
} else if (
(obj[i].type === undefined && obj[i].data === undefined) ||
(obj[i].type &&
obj[i].type !== "created" &&
obj[i].type !== "unchanged")
) {
const partial = isNaN(parseInt(i, 10)) ? `.${i}` : `[${i}]`;
name = path !== null ? path + partial : i;
// console.log("- nested object ->", name, obj[i].dataType);
updateList = updateList.concat(filterOutCreateFields(obj[i], name));
}
}
}
// console.log("returning updateList: " + updateList);
return updateList;
};
const updateList = filterOutCreateFields(compareResult, null);
updateList.forEach(expr => {
const propName = expr.name
.replace(/&/g, "")
.replace(/_/g, "")
.replace(/\[/g, "")
.replace(/\]/g, "");
let splittedByDotPropName, propNameExpressionName;
if (expr.dataType !== "list") {
splittedByDotPropName = expr.name.split(".");
propNameExpressionName = `#${splittedByDotPropName
.map(removeSpecialChars)
.join(".#")}`;
splittedByDotPropName.forEach(partialName => {
request.ExpressionAttributeNames[
`#${removeSpecialChars(partialName)}`
] = partialName;
});
if (hasRemoveExpression) {
removeExpression += `, ${propNameExpressionName}`;
} else {
removeExpression += `REMOVE ${propNameExpressionName}`;
hasRemoveExpression = true;
}
} else if (expr.value && expr.value.length === 0) {
splittedByDotPropName = expr.name.split(".");
propNameExpressionName = `#${splittedByDotPropName
.map(removeSpecialChars)
.join(".#")}`;
splittedByDotPropName.forEach(partialName => {
request.ExpressionAttributeNames[
`#${removeSpecialChars(partialName)}`
] = partialName;
});
if (hasRemoveExpression) {
removeExpression += `, ${propNameExpressionName}`;
} else {
removeExpression += `REMOVE ${propNameExpressionName}`;
hasRemoveExpression = true;
}
}
});
// List element updates
updateList.forEach(expr => {
const propName = expr.name
.replace(/&/g, "")
.replace(/_/g, "")
.replace(/\[/g, "")
.replace(/\]/g, "");
let splittedByDotPropName, propNameExpressionName, propNameExpressionValue;
if (expr.dataType !== "list") {
} else {
let value = null;
// Remove any elements that specified in removes json
if (
typeof _.get(original, expr.name)[0] === "object" ||
typeof _.get(removes, expr.name)[0] === "object"
) {
if (typeof itemUniqueId === "undefined" || itemUniqueId == null) {
console.error(
"Found object in a list, but no itemUniqueId parameter specified"
);
value = _.xorBy(
_.get(original, expr.name),
_.get(removes, expr.name),
"id"
);
} else {
value = _.xorBy(
_.get(original, expr.name),
_.get(removes, expr.name),
itemUniqueId
);
}
} else {
value = _.xor(_.get(original, expr.name), _.get(removes, expr.name));
}
splittedByDotPropName = expr.name.split(".");
propNameExpressionName = `#${splittedByDotPropName
.map(removeSpecialChars)
.join(".#")}`;
splittedByDotPropName.forEach(partialName => {
request.ExpressionAttributeNames[
`#${removeSpecialChars(partialName)}`
] = partialName;
});
propNameExpressionValue = `:${removeSpecialChars(propName)}`;
if (value.length === 0) {
// Remove
if (hasRemoveExpression) {
// subsequent elements
removeExpression += `, ${propNameExpressionName}`;
} else {
// first element
removeExpression = `REMOVE ${propNameExpressionName}`;
hasRemoveExpression = true;
}
} else {
// Set/Update
request.ExpressionAttributeValues[propNameExpressionValue] = value;
if (hasSetExpression) {
// Subsequent element
setExpression += `, ${propNameExpressionName} = ${propNameExpressionValue}`;
} else {
setExpression = `SET ${propNameExpressionName} = ${propNameExpressionValue}`;
hasSetExpression = true;
}
}
}
});
if (isEmpty(request.ExpressionAttributeNames)) {
delete request.ExpressionAttributeNames;
}
if (isEmpty(request.ExpressionAttributeValues)) {
delete request.ExpressionAttributeValues;
}
if (hasSetExpression && hasRemoveExpression) {
request.UpdateExpression = `${removeExpression.trim()} ${setExpression.trim()}`;
} else if (hasSetExpression) {
request.UpdateExpression = setExpression.trim();
} else if (hasRemoveExpression) {
request.UpdateExpression = removeExpression.trim();
}
return request;
};
// make sure the ES5 Array.isArray() method exists
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === "[object Array]";
};
}
function emptyArrays(data) {
for (const key of Object.keys(data)) {
if (key !== undefined) {
// console.log("key: ", key);
const item = data[key];
if (item !== undefined && Array.isArray(item)) {
// see if the array is empty
// remove this item from the parent object
// console.log("deleting the item:" + JSON.stringify(item));
data[key] = [];
// if this item is an object, then recurse into it
// to remove empty arrays in it too
} else if (item !== undefined && typeof item === "object") {
emptyArrays(item);
}
}
}
}
export function getRemoveExpression(removes, original = {}, itemUniqueId) {
return removeExpressionGenerator(
original,
removes,
deepDiffMapper.map(removes, original),
null,
itemUniqueId
);
}
export function getUpdateExpression(updates, original = {}, options) {
if (options && options.arrayMerge && options.arrayMerge === "replaceMerge") {
emptyArrays(original);
delete options.arrayMerge;
}
const merged = merge(original, updates);
return updateExpressionGenerator(
deepDiffMapper.map(original, merged),
options,
null
);
}