@trusthab/composable-resources
Version:
migrating https://github.com/knetikmedia/hab-api/tree/integration/app/resources/composable
89 lines (67 loc) • 2.66 kB
JavaScript
const _ = require('lodash');
const composer = require('../mixin_loader');
module.exports = (App) => {
const { underscore } = require('inflected');
const ErrorService = App.get('Services.Utils.ErrorService');
class MetricDatapointPersistenceResource {
delete() {
const promise = Promise.resolve();
return promise.then(() => deleteDatapoint.call(this))
.catch(err => handleError(err));
}
save() {
let promise = Promise.resolve();
if (this.isTimingBased()) { promise = this.setTimerValue(); }
return promise.then(() => (this.customDimensions()
? sendDatapoint.call(this)
: sendAsExpandedLocations.call(this)))
.catch(err => handleError(err));
}
}
function handleError(error) {
const service = new ErrorService(error);
return service.result();
}
function sendAsExpandedLocations() {
const { identifier, ...locations } = this.getDimensions();
const location_ids = _.pickBy(locations, i => !_.isNull(i) && !_.isUndefined(i));
const tasks = [];
Object.keys(location_ids).forEach(key => tasks.push(sendLocationDatapoint.bind(this, key)));
// Sequential update
return tasks.reduce(
(promise, task) => promise.then(task),
Promise.resolve(),
);
}
function deleteDatapoint() {
const data = this.serialize();
const { id, dimensions } = data;
return App.KCTmp.deleteDatapoint(id, dimensions)
.then(() => {
return App.Logger.info(`Metric Datapoint Persistence: Metric Delete`, id, dimensions)
});
}
function sendDatapoint() {
const data = this.serialize();
const { id } = data;
const metricDatapoint = _.cloneDeep(data);
const api = App.KnetikCloud.get('MonitoringApi');
return api.postDatapoint(id, { metricDatapoint })
.then(() => App.Logger.info(`Metric Datapoint Persistence: Metric Sent`, metricDatapoint));
}
function sendLocationDatapoint(key) {
const data = this.serialize();
if (this.isValueBased() && !this.hasValue()) {
App.Logger.info(`Metric Datapoint Persistence: KPI without value`, data);
return Promise.resolve();
}
const { id, dimensions } = data;
const { identifier, ...locations } = dimensions;
const metricDatapoint = _.cloneDeep(data);
metricDatapoint.dimensions = { identifier, location_id: locations[key] };
const api = App.KnetikCloud.get('MonitoringApi');
return api.postDatapoint(id, { metricDatapoint })
.then(() => App.Logger.info(`Metric Datapoint Persistence: Metric Sent`, metricDatapoint));
}
return composer(MetricDatapointPersistenceResource, App);
};