1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-22 19:07:54 +01:00
unleash.unleash/packages/unleash-api/lib/eventDiffer.js

78 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-06-18 21:53:18 +02:00
'use strict';
2016-06-20 10:27:19 +02:00
const eventType = require('./eventType');
const diff = require('deep-diff').diff;
2016-06-18 21:53:18 +02:00
const strategyTypes = [
eventType.strategyCreated,
2016-06-18 21:55:46 +02:00
eventType.strategyDeleted,
];
2016-06-18 21:53:18 +02:00
const featureTypes = [
eventType.featureCreated,
eventType.featureUpdated,
2015-02-09 18:28:51 +01:00
eventType.featureArchived,
2016-06-18 21:55:46 +02:00
eventType.featureRevived,
];
2016-07-02 11:54:50 +02:00
function baseTypeFor (event) {
if (featureTypes.indexOf(event.type) !== -1) {
return 'features';
} else if (strategyTypes.indexOf(event.type) !== -1) {
return 'strategies';
}
2016-06-18 22:23:19 +02:00
throw new Error(`unknown event type: ${JSON.stringify(event)}`);
}
2016-07-02 11:54:50 +02:00
function groupByBaseTypeAndName (events) {
2016-06-18 21:53:18 +02:00
const groups = {};
2016-06-18 21:53:18 +02:00
events.forEach(event => {
const baseType = baseTypeFor(event);
groups[baseType] = groups[baseType] || {};
groups[baseType][event.data.name] = groups[baseType][event.data.name] || [];
groups[baseType][event.data.name].push(event);
});
return groups;
}
2016-07-02 11:54:50 +02:00
function eachConsecutiveEvent (events, callback) {
2016-06-18 21:53:18 +02:00
const groups = groupByBaseTypeAndName(events);
2016-06-18 21:53:18 +02:00
Object.keys(groups).forEach(baseType => {
const group = groups[baseType];
2016-06-18 21:53:18 +02:00
Object.keys(group).forEach(name => {
2016-06-18 22:23:19 +02:00
const currentEvents = group[name];
2016-06-18 21:53:18 +02:00
let left;
let right;
let i;
let l;
2016-06-18 22:23:19 +02:00
for (i = 0, l = currentEvents.length; i < l; i++) {
left = currentEvents[i];
right = currentEvents[i + 1];
callback(left, right);
}
});
});
}
2016-07-02 11:54:50 +02:00
function addDiffs (events) {
2016-06-18 21:53:18 +02:00
eachConsecutiveEvent(events, (left, right) => {
if (right) {
left.diffs = diff(right.data, left.data);
left.diffs = left.diffs || [];
} else {
left.diffs = null;
}
});
}
module.exports = {
2016-06-18 21:55:46 +02:00
addDiffs,
};