-
Notifications
You must be signed in to change notification settings - Fork 1
/
transform-data.js
49 lines (42 loc) · 1.46 KB
/
transform-data.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
'use strict';
module.exports = function transformData (prefix, data) {
// Setting the last modified key will yield incorrect result when deleting a key.
// Basically we do not catch deleted keys.
// If ModifyIndex is a running counter and we would store the latest index then we could see if we go backwards,
// but we wouldn't know which key without comparing the old configuration against the new, and if we
// would do that then we wouldn't need to keep track on the index.
var modifyIndex = 0;
return data.reduce(function (result, item) {
var keyPath = clean(item.Key).split('/').filter(Boolean);
if (!keyPath.length) return result;
var key = keyPath.pop();
var inner = createParent(keyPath, result);
inner[key] = parseValue(item);
if (item.ModifyIndex > modifyIndex) {
modifyIndex = item.ModifyIndex;
result._last_modified_key = clean(item.Key);
}
return result;
}, {
_modified_time: new Date().toJSON()
});
function clean (key) {
return key.replace(prefix, '');
}
function createParent (keyPath, initial) {
return keyPath.reduce(function (inner, parent) {
if (inner[parent] === undefined) inner[parent] = {};
return inner[parent];
}, initial);
}
function parseValue (item) {
if (item.Value === null && item.Key.slice(-1) === '/') return {};
var value;
try {
value = JSON.parse(item.Value);
} catch (e) {
value = item.Value;
}
return value;
}
};