@trusthab/composable-resources
Version:
migrating https://github.com/knetikmedia/hab-api/tree/integration/app/resources/composable
113 lines (84 loc) • 2.44 kB
JavaScript
const composer = require('../mixin_loader');
const _ = require('lodash');
const moment = require('moment');
const { underscore } = require('inflected');
const cachedValues = {};
module.exports = App => {
class MetricTimerResource {
customMetricType() {
const type = this.get('metric_type');
if (type) { return type; }
return 'timer';
}
shouldRun() {
return false;
}
setTimerValue() {
// on start
//
// if prev-value is null, value is set to 0 and the current timestsamp is cached
// if prev-value >= 0 value is now - prev-value, then current timestamp is cached
//
// on stop
//
// prev-value is set to null and cache is removed
this.set({ metric_type: 'counter' });
if (_.isUndefined(this.shouldRun())) {
this.set({value: undefined});
return Promise.resolve(undefined);
}
const promise = this.shouldRun() ? run.call(this) : stop.call(this);
App.Logger.info(
`Metric Datapoint Persistence: Metric Built ${
this.metric_id
} (${this.shouldRun()})`,
);
return promise;
}
newVal(val, time) {
return parseInt(val) + (moment().unix() - parseInt(time));
}
}
function getCachedValue() {
const value = cachedValues[this.cacheName()];
if (value) {
return Promise.resolve(value);
}
return App.CredentialsStore.get(this.cacheName());
}
function run() {
return getCachedValue.call(this).then(prev => {
const value = getRunningValue.call(this, prev);
this.set({value});
const newVal = `${moment()
.unix()
.toString()}-${value}`;
cachedValues[this.cacheName()] = newVal;
// allow async value cache
App.CredentialsStore.set(this.cacheName(), newVal);
return Promise.resolve(newVal);
});
}
function getRunningValue(prev) {
let time;
let val;
if (prev) {
const [prev_time, prev_value] = prev.split('-');
time = prev_time;
val = prev_value;
}
if (!prev) {
time = moment().unix();
val = 0;
}
const value = prev ? this.newVal(val, time) : 0;
return value;
}
function stop() {
this.set({value: 0});
// allow async value removal
App.CredentialsStore.remove(this.cacheName());
return Promise.resolve(null);
}
return composer(MetricTimerResource, App);
};