This repository has been archived by the owner on Mar 31, 2024. It is now read-only.
forked from elastic/kibana
-
Notifications
You must be signed in to change notification settings - Fork 3
/
_delayed_updater.js
85 lines (71 loc) · 2.06 KB
/
_delayed_updater.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
import _ from 'lodash';
import angular from 'angular';
import ConfigValsProvider from 'ui/config/_vals';
export default function DelayedUpdaterFactory(Private, $rootScope, Promise, Notifier) {
var notify = new Notifier();
var vals = Private(ConfigValsProvider);
return function DelayedUpdater(doc) {
var updater = this;
var queue = [];
var log = {};
var timer;
updater.fire = function () {
clearTimeout(timer);
// only fire once
if (updater.fired) return;
updater.fired = true;
var method;
var body;
var updated = [];
var deleted = [];
// seperate the log into lists
Object.keys(log).forEach(function (key) {
if (log[key] === 'updated') updated.push(key);
else deleted.push(key);
});
if (deleted.length) {
method = 'doIndex';
body = _.clone(vals);
} else {
method = 'doUpdate';
body = _.pick(vals, updated);
}
doc[method](vals)
.then(
function (resp) {
queue.forEach(function (q) { q.resolve(resp); });
},
function (err) {
queue.forEach(function (q) { q.reject(err); });
}
)
.finally(function () {
$rootScope.$broadcast('change:config', updated.concat(deleted));
});
};
updater.update = function (key, val, silentAndLocal) {
var newVal = val;
var oldVal = vals[key];
if (angular.equals(newVal, oldVal)) {
return Promise.resolve();
}
else if (newVal == null) {
delete vals[key];
log[key] = 'deleted';
}
else {
vals[key] = newVal;
log[key] = 'updated';
}
if (silentAndLocal) return Promise.resolve();
var defer = Promise.defer();
queue.push(defer);
notify.log('config change: ' + key + ': ' + oldVal + ' -> ' + newVal);
$rootScope.$broadcast('change:config.' + key, newVal, oldVal);
// reset the fire timer
clearTimeout(timer);
timer = setTimeout(updater.fire, 200);
return defer.promise;
};
};
};