@trusthab/composable-resources
Version:
migrating https://github.com/knetikmedia/hab-api/tree/integration/app/resources/composable
131 lines (108 loc) • 2.71 kB
JavaScript
const moment = require('moment');
const _ = require('lodash');
const composer = require('../mixin_loader');
const TIMING_BASED_METRICS = ['delta', 'timer'];
const VALUES_BASED_METRICS = ['counter', 'gauge'];
const METRIC_TYPES = [...TIMING_BASED_METRICS, ...VALUES_BASED_METRICS];
const DEFAULT_METRIC_TYPE = 'gauge';
module.exports = (App) => {
class KpiResource {
static mixins() {
return [
'Validatable',
'MetricDatapointPersistence'
];
}
static fields() {
return {
obj: {
type: 'object',
schema_ignore: true
},
diff: {
type: 'object',
schema_ignore: true
},
transaction: {
type: 'text',
schema_ignore: true
},
id: {
type: 'text',
get_method: 'getMetricId'
},
metric_type: {
type: 'text',
get_method: 'getMetricType',
schema_ignore: true
},
timestamp: {
type: 'integer',
get_method: 'getTimestamp'
},
value: {
type: 'double',
get_method: 'getValue'
},
dimensions: {
type: 'object',
get_method: 'getDimensions'
}
};
}
getMetricId() {
return this.get('metric_id');
}
getMetricType() {
if (this.customMetricType) { return this.customMetricType(); }
const metricType = this.get('metric_type');
if (METRIC_TYPES.includes(metricType)) { return metricType; }
return DEFAULT_METRIC_TYPE;
}
getRequest() {
return undefined;
}
getTimestamp() {
return this.get('timestamp') || moment().unix();
}
getValue() {
return this.get('value');
}
customDimensions() {
return false;
}
getDimensions() {
const obj = this.get('obj');
const dimensions = _.pick(obj, [
'id',
'location_id',
'parent_location_id',
'root_location_id'
]);
const { id, ...location_properties } = dimensions;
return {
identifier: this.getIdentifier() || id,
...location_properties
};
}
cacheName() {
return `${this.metric_id}-${this.getIdentifier() || this.get('obj').id}`;
}
getIdentifier() {
return undefined;
}
isDeletable() {
return false;
}
isTimingBased() {
return TIMING_BASED_METRICS.includes(this.getMetricType());
}
isValueBased() {
return VALUES_BASED_METRICS.includes(this.getMetricType());
}
hasValue() {
return !_.isNil(this.getValue());
}
}
return composer(KpiResource, App);
};