diff --git a/src/alert/alert.js b/src/alert/alert.js index 31312ce..5445d18 100644 --- a/src/alert/alert.js +++ b/src/alert/alert.js @@ -1,51 +1,49 @@ -function Alert(opts) { - opts = opts || {}; - this.conditions = []; - - this.state = { - name: 'Panel Title alert', - for: '15m', - frequency: '5m', - conditions: [], - message: '', - notifications: [], - executionErrorState: 'keep_state', - noDataState: 'keep_state', - alertRuleTags: {}, - handler: 1, - }; - - this._init(opts); - this._initConditions(opts); -} +class Alert { + constructor(opts = {}) { + this.conditions = []; + + this.state = { + name: 'Panel Title alert', + for: '15m', + frequency: '5m', + conditions: [], + message: '', + notifications: [], + executionErrorState: 'keep_state', + noDataState: 'keep_state', + alertRuleTags: {}, + handler: 1, + }; + + this._init(opts); + this._initConditions(opts); + } -Alert.prototype._init = function _init(opts) { - const self = this; + _init(opts) { + Object.keys(opts).forEach((opt) => { + this.state[opt] = opts[opt]; + }); + } - Object.keys(opts).forEach(function eachOpt(opt) { - self.state[opt] = opts[opt]; - }); -}; + _initConditions(opts) { + this.state.conditions = this.state.conditions || []; -Alert.prototype._initConditions = function _initConditions(opts) { - var self = this; - this.state.conditions = this.state.conditions || []; + if (opts.conditions) { + this.conditions = this.conditions.concat(opts.conditions); + } + } - if (opts.conditions) { - self.conditions = self.conditions.concat(opts.conditions); + addCondition(condition) { + this.conditions.push(condition); + return this; } -}; - -Alert.prototype.addCondition = function addCondition(condition) { - this.conditions.push(condition); - return this; -}; - -Alert.prototype.generate = function generate() { - this.state.conditions = this.conditions.map((condition) => - condition.generate() - ); - return this.state; -}; + + generate() { + this.state.conditions = this.conditions.map((condition) => + condition.generate() + ); + return this.state; + } +} module.exports = Alert; diff --git a/src/alert/condition.js b/src/alert/condition.js index 28bb6d0..da26755 100644 --- a/src/alert/condition.js +++ b/src/alert/condition.js @@ -1,84 +1,77 @@ -function Condition(opts) { - opts = opts || {}; - - const that = this; - that.state = {}; - - this._evaluator = { - params: [], - type: 'gt', - }; - - this._operator = { - type: 'and', - }; - - this._query = { - params: ['A', '5m', 'now'], - }; - - this._reducer = { - params: [], - type: 'avg', - }; - - Object.keys(opts).forEach(function eachOpt(opt) { - that.state[opt] = opts[opt]; - }); - - function withEvaluator(value, type) { +class Condition { + constructor(opts = {}) { + this.state = {}; + + this._evaluator = { + params: [], + type: 'gt', + }; + + this._operator = { + type: 'and', + }; + + this._query = { + params: ['A', '5m', 'now'], + }; + + this._reducer = { + params: [], + type: 'avg', + }; + + Object.keys(opts).forEach((opt) => { + this.state[opt] = opts[opt]; + }); + } + withEvaluator(value, type) { const types = ['gt', 'lt', 'within_range']; if (!types.includes(type)) { throw Error(`Evaluator type must be one of [${types.toString()}]`); } - that._evaluator.type = type; + this._evaluator.type = type; if (['gt', 'lt'].includes(type)) { - that._evaluator.params = [value]; + this._evaluator.params = [value]; } else if (Array.isArray(value)) { - that._evaluator.params = value; + this._evaluator.params = value; } return this; } - - function withOperator(operator) { + withOperator(operator) { const types = ['and', 'or']; if (!types.includes(operator)) { throw Error(`Operator must be one of [${types.toString}]`); } - that._operator.type = operator; + this._operator.type = operator; return this; } - - function orCondition() { - that._operator.type = 'or'; + orCondition() { + this._operator.type = 'or'; return this; } - - function andCondition() { - that._operator.type = 'and'; + andCondition() { + this._operator.type = 'and'; return this; } - - function onQuery(query, duration, from) { + onQuery(query, duration, from) { if (typeof query !== 'string') { throw Error( 'Query identifier must be a string. eg. "A" or "B", etc...' ); } - that._query.params[0] = query; - that._query.params[1] = duration; - that._query.params[2] = from; + this._query.params[0] = query; + this._query.params[1] = duration; + this._query.params[2] = from; return this; } - - function withReducer(type) { + withReducer(type) { const types = [ 'min', 'max', @@ -94,33 +87,22 @@ function Condition(opts) { throw Error(`Reducer has to be one of [${types.toString()}]`); } - that._reducer.type = type; + this._reducer.type = type; return this; } - - function generate() { + generate() { return Object.assign( {}, { - evaluator: that._evaluator, - operator: that._operator, - query: that._query, - reducer: that._reducer, + evaluator: this._evaluator, + operator: this._operator, + query: this._query, + reducer: this._reducer, type: 'query', }, - that.state + this.state ); } - - return { - withEvaluator, - withOperator, - withReducer, - orCondition, - andCondition, - onQuery, - generate, - }; } module.exports = Condition; diff --git a/src/annotations/graphite.js b/src/annotations/graphite.js index 7856f78..a547a09 100644 --- a/src/annotations/graphite.js +++ b/src/annotations/graphite.js @@ -22,50 +22,49 @@ var errors = require('../errors'); -function Graphite(opts) { - opts = opts || {}; - var self = this; +class Graphite { + constructor(opts = {}) { + if (!opts.name) { + throw errors.UnfulfilledRequirement.create( + '{component} missing requirement: {unfulfilledArg}', + { + component: 'grafana.annotations.Graphite', + unfulfilledArg: 'name', + } + ); + } - if (!opts.name) { - throw errors.UnfulfilledRequirement.create( - '{component} missing requirement: {unfulfilledArg}', - { - component: 'grafana.annotations.Graphite', - unfulfilledArg: 'name', - } - ); - } + if (!opts.target) { + throw errors.UnfulfilledRequirement.create( + '{component} missing requirement: {unfulfilledArg}', + { + component: 'grafana.annotations.Graphite', + unfulfilledArg: 'target', + } + ); + } - if (!opts.target) { - throw errors.UnfulfilledRequirement.create( - '{component} missing requirement: {unfulfilledArg}', - { - component: 'grafana.annotations.Graphite', - unfulfilledArg: 'target', - } - ); - } + var defaults = { + name: 'no name', + datasource: 'graphite', + showLine: true, + iconColor: 'rgb(255, 234, 0)', + lineColor: 'rgba(165, 161, 70, 0.59)', + iconSize: 10, + enable: true, + target: '', + }; + this.state = defaults; - var defaults = { - name: 'no name', - datasource: 'graphite', - showLine: true, - iconColor: 'rgb(255, 234, 0)', - lineColor: 'rgba(165, 161, 70, 0.59)', - iconSize: 10, - enable: true, - target: '', - }; - self.state = defaults; + // Overwrite defaults with custom values + Object.keys(opts).forEach((opt) => { + this.state[opt] = opts[opt]; + }); + } - // Overwrite defaults with custom values - Object.keys(opts).forEach(function eachOpt(opt) { - self.state[opt] = opts[opt]; - }); + generate() { + return this.state; + } } -Graphite.prototype.generate = function generate() { - return this.state; -}; - module.exports = Graphite; diff --git a/src/dashboard.js b/src/dashboard.js index a8326d3..3ded0b5 100644 --- a/src/dashboard.js +++ b/src/dashboard.js @@ -24,108 +24,103 @@ var Templates = require('./templates'); var Annotations = require('./annotations'); var ExternalLink = require('./external-link'); -function Dashboard(opts) { - opts = opts || {}; - this.state = {}; - this._init(opts); - this._initRows(opts); - this._initLinks(opts); - this._initTemplating(opts); - this._initAnnotations(opts); -} - -Dashboard.prototype._init = function _init(opts) { - this.state.id = opts.id || null; - this.state.title = opts.title || 'Generated Grafana Dashboard'; - this.state.originalTitle = opts.originalTitle || 'Generated Dashboard'; - this.state.tags = opts.tags || []; - this.state.style = opts.style || 'dark'; - this.state.timezone = opts.timezone || 'browser'; - this.state.editable = true; - this.state.hideControls = !!opts.hideControls; - this.state.sharedCrosshair = !!opts.sharedCrosshair; - this.state.refresh = opts.refresh || false; - this.state.schemaVersion = opts.schemaVersion || 6; - this.state.hideAllLegends = !!opts.hideAllLegends; - this.state.time = opts.time || null; - if ('editable' in opts) { - this.state.editable = opts.editable; +class Dashboard { + constructor(opts = {}) { + this.state = {}; + this._init(opts); + this._initRows(opts); + this._initLinks(opts); + this._initTemplating(opts); + this._initAnnotations(opts); } -}; -Dashboard.prototype._initRows = function _initRows(opts) { - var self = this; + _init(opts) { + this.state.id = opts.id || null; + this.state.title = opts.title || 'Generated Grafana Dashboard'; + this.state.originalTitle = opts.originalTitle || 'Generated Dashboard'; + this.state.tags = opts.tags || []; + this.state.style = opts.style || 'dark'; + this.state.timezone = opts.timezone || 'browser'; + this.state.editable = true; + this.state.hideControls = !!opts.hideControls; + this.state.sharedCrosshair = !!opts.sharedCrosshair; + this.state.refresh = opts.refresh || false; + this.state.schemaVersion = opts.schemaVersion || 6; + this.state.hideAllLegends = !!opts.hideAllLegends; + this.state.time = opts.time || null; + if ('editable' in opts) { + this.state.editable = opts.editable; + } + } - this.rows = []; - this.state.rows = []; + _initRows(opts) { + this.rows = []; + this.state.rows = []; - if (opts.rows) { - opts.rows.forEach(function r(row) { - self.addRow(row); - }); + if (opts.rows) { + opts.rows.forEach((row) => { + this.addRow(row); + }); + } } -}; -Dashboard.prototype._initLinks = function _initLinks(opts) { - this.links = opts.links || []; - this.state.links = []; -}; + _initLinks(opts) { + this.links = opts.links || []; + this.state.links = []; + } -Dashboard.prototype._initTemplating = function _initRows(opts) { - var self = this; + _initTemplating(opts) { + this.state.templating = { + list: [], + enable: true, + }; + + if (opts.templating) { + opts.templating.forEach((template) => { + template = new Templates.Custom(template); + this.addTemplate(template); + }); + } + } - this.state.templating = { - list: [], - enable: true, - }; + _initAnnotations(opts) { + this.state.annotations = { + list: [], + enable: true, + }; + + if (opts.annotations) { + opts.annotations.forEach((annotation) => { + annotation = new Annotations.Graphite(annotation); + this.addAnnotation(annotation); + }); + } + } - if (opts.templating) { - opts.templating.forEach(function temp(template) { - template = new Templates.Custom(template); - self.addTemplate(template); - }); + addRow(row) { + this.rows.push(row); } -}; -Dashboard.prototype._initAnnotations = function _initAnnotations(opts) { - var self = this; + addTemplate(template) { + this.state.templating.list.push(template.generate()); + } - this.state.annotations = { - list: [], - enable: true, - }; + addAnnotation(annotation) { + this.state.annotations.list.push(annotation.generate()); + } - if (opts.annotations) { - opts.annotations.forEach(function temp(annotation) { - annotation = new Annotations.Graphite(annotation); - self.addAnnotation(annotation); + generate() { + // Generate jsons. + this.state.rows = this.rows.map((row) => row.generate()); + this.state.links = this.links.map((link) => { + if (link instanceof ExternalLink) { + return link.generate(); + } + return link; }); - } -}; - -Dashboard.prototype.addRow = function addRow(row) { - this.rows.push(row); -}; - -Dashboard.prototype.addTemplate = function addTemplate(template) { - this.state.templating.list.push(template.generate()); -}; - -Dashboard.prototype.addAnnotation = function addAnnotation(annotation) { - this.state.annotations.list.push(annotation.generate()); -}; - -Dashboard.prototype.generate = function generate() { - // Generate jsons. - this.state.rows = this.rows.map((row) => row.generate()); - this.state.links = this.links.map((link) => { - if (link instanceof ExternalLink) { - return link.generate(); - } - return link; - }); - return this.state; -}; + return this.state; + } +} module.exports = Dashboard; diff --git a/src/external-link.js b/src/external-link.js index de6983e..50361d0 100644 --- a/src/external-link.js +++ b/src/external-link.js @@ -18,50 +18,47 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -'use strict'; - -function ExternalLink(opts) { - opts = opts || {}; - - const defaults = { - title: '', - tooltip: '', - url: '', - ...opts, - tags: [], - icon: 'external link', - targetBlank: true, - type: 'link', - includeVars: false, - keepTime: false, - }; - this.state = defaults; -} - -ExternalLink.prototype.generate = function generate() { - if (this.state.title === '') { - throw new SyntaxError('a title for the link must be provided'); +class ExternalLink { + constructor(opts = {}) { + const defaults = { + title: '', + tooltip: '', + url: '', + ...opts, + tags: [], + icon: 'external link', + targetBlank: true, + type: 'link', + includeVars: false, + keepTime: false, + }; + this.state = defaults; } - if (this.state.url === '') { - throw new SyntaxError('a url for the link must be provided'); + + generate() { + if (this.state.title === '') { + throw new SyntaxError('a title for the link must be provided'); + } + if (this.state.url === '') { + throw new SyntaxError('a url for the link must be provided'); + } + return this.state; } - return this.state; -}; -ExternalLink.prototype.includeVariableValues = - function includeVariableValues() { + includeVariableValues() { this.state.includeVars = true; return this; - }; + } -ExternalLink.prototype.includeTimeFilter = function includeTimeFilter() { - this.state.keepTime = true; - return this; -}; + includeTimeFilter() { + this.state.keepTime = true; + return this; + } -ExternalLink.prototype.withIcon = function withIcon(iconName) { - this.state.icon = iconName; - return this; -}; + withIcon(iconName) { + this.state.icon = iconName; + return this; + } +} module.exports = ExternalLink; diff --git a/src/panels/dashboard_list.js b/src/panels/dashboard_list.js index dc62853..ea953bc 100644 --- a/src/panels/dashboard_list.js +++ b/src/panels/dashboard_list.js @@ -22,43 +22,42 @@ var generateGraphId = require('../id'); -function DashboardList(opts) { - opts = opts || {}; - var self = this; - - this.state = { - title: 'dashboard list', - error: false, - span: 3, - editable: true, - type: 'dashlist', - isNew: true, - id: generateGraphId(), - mode: 'search', - query: 'dashboard list', - limit: 10, - tags: [], - links: [], - }; +class DashboardList { + constructor(opts = {}) { + this.state = { + title: 'dashboard list', + error: false, + span: 3, + editable: true, + type: 'dashlist', + isNew: true, + id: generateGraphId(), + mode: 'search', + query: 'dashboard list', + limit: 10, + tags: [], + links: [], + }; + + // Overwrite defaults with custom values + Object.keys(opts).forEach((opt) => { + this.state[opt] = opts[opt]; + }); + + // finally add to row/dashboard if given + if (opts.row && opts.dashboard) { + opts.row.addPanel(this); + opts.dashboard.addRow(opts.row); + } + } - // Overwrite defaults with custom values - Object.keys(opts).forEach(function eachOpt(opt) { - self.state[opt] = opts[opt]; - }); + setTitle(title) { + this.state.title = title; + } - // finally add to row/dashboard if given - if (opts.row && opts.dashboard) { - opts.row.addPanel(this); - opts.dashboard.addRow(opts.row); + generate() { + return this.state; } } -DashboardList.prototype.setTitle = function setTitle(title) { - this.state.title = title; -}; - -DashboardList.prototype.generate = function generate() { - return this.state; -}; - module.exports = DashboardList; diff --git a/src/panels/graph.js b/src/panels/graph.js index 39184c5..10c2b39 100644 --- a/src/panels/graph.js +++ b/src/panels/graph.js @@ -22,104 +22,104 @@ const generateGraphId = require('../id'); -function Graph(opts) { - opts = opts || {}; - const self = this; - this._currentRefIndex = 0; - - const defaults = { - type: 'graph', - id: generateGraphId(), - renderer: 'flot', - title: 'no title (click here)', - error: false, - editable: true, - 'x-axis': true, - 'y-axis': true, - y_formats: ['short', 'short'], - grid: { - leftMax: null, - rightMax: null, - leftMin: null, - rightMin: null, - threshold1: null, - threshold2: null, - threshold1Color: 'rgba(216, 200, 27, 0.27)', - threshold2Color: 'rgba(234, 112, 112, 0.22)', - }, - lines: true, - span: 12, - fill: 0, - linewidth: 1, - points: false, - pointradius: 5, - bars: false, - stack: false, - percentage: false, - targets: [], - legend: { - show: true, - values: true, - min: false, - max: true, - current: false, - total: false, - avg: true, - }, - nullPointMode: 'null as zero', - steppedLine: false, - tooltip: { - value_type: 'cumulative', - shared: false, - }, - aliasColors: {}, - seriesOverrides: [{}], - links: [], - datasource: 'graphite', - }; - this.state = defaults; - - // Overwrite defaults with custom values - Object.keys(opts).forEach(function eachOpt(opt) { - self.state[opt] = opts[opt]; - }); - - if (opts.targets) { - this.state.targets = []; - opts.targets.forEach(function addT(target) { - self.addTarget(target); +class Graph { + constructor(opts = {}) { + this._currentRefIndex = 0; + + const defaults = { + type: 'graph', + id: generateGraphId(), + renderer: 'flot', + title: 'no title (click here)', + error: false, + editable: true, + 'x-axis': true, + 'y-axis': true, + y_formats: ['short', 'short'], + grid: { + leftMax: null, + rightMax: null, + leftMin: null, + rightMin: null, + threshold1: null, + threshold2: null, + threshold1Color: 'rgba(216, 200, 27, 0.27)', + threshold2Color: 'rgba(234, 112, 112, 0.22)', + }, + lines: true, + span: 12, + fill: 0, + linewidth: 1, + points: false, + pointradius: 5, + bars: false, + stack: false, + percentage: false, + targets: [], + legend: { + show: true, + values: true, + min: false, + max: true, + current: false, + total: false, + avg: true, + }, + nullPointMode: 'null as zero', + steppedLine: false, + tooltip: { + value_type: 'cumulative', + shared: false, + }, + aliasColors: {}, + seriesOverrides: [{}], + links: [], + datasource: 'graphite', + }; + this.state = defaults; + + // Overwrite defaults with custom values + Object.keys(opts).forEach((opt) => { + this.state[opt] = opts[opt]; }); - } - // finally add to row/dashboard if given - if (opts.row && opts.dashboard) { - opts.row.addPanel(this); - opts.dashboard.addRow(opts.row); + if (opts.targets) { + this.state.targets = []; + opts.targets.forEach((target) => { + this.addTarget(target); + }); + } + + // finally add to row/dashboard if given + if (opts.row && opts.dashboard) { + opts.row.addPanel(this); + opts.dashboard.addRow(opts.row); + } } -} -Graph.prototype.generate = function generate() { - return this.state; -}; + generate() { + return this.state; + } -Graph.prototype.addAlert = function addAlert(alert) { - this.state.alert = alert.generate(); -}; + addAlert(alert) { + this.state.alert = alert.generate(); + } -Graph.prototype.addTarget = function addTarget(target) { - const refs = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - const builtTarget = target.toString(); + addTarget(target) { + const refs = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + const builtTarget = target.toString(); - const targetWithRefs = { - target: builtTarget, - hide: target.hide, - refId: refs[this._currentRefIndex++], - }; + const targetWithRefs = { + target: builtTarget, + hide: target.hide, + refId: refs[this._currentRefIndex++], + }; - const targetFull = handleRefTargets(builtTarget, this.state.targets); - const targetToAdd = Object.assign({}, targetWithRefs, targetFull); - this.state.targets.push(targetToAdd); -}; + const targetFull = handleRefTargets(builtTarget, this.state.targets); + const targetToAdd = Object.assign({}, targetWithRefs, targetFull); + this.state.targets.push(targetToAdd); + } +} function getRefsFromTarget(target) { const refMatchRegex = /.*?#(\w)[,)]/g; diff --git a/src/panels/singlestat.js b/src/panels/singlestat.js index 72e815d..35a5737 100644 --- a/src/panels/singlestat.js +++ b/src/panels/singlestat.js @@ -22,87 +22,86 @@ var generateGraphId = require('../id'); -function SingleStat(opts) { - opts = opts || {}; - var self = this; - - var defaults = { - id: generateGraphId(), - title: 'single stat', - targets: [], - error: false, - span: 12, - editable: true, - type: 'singlestat', - links: [], - maxDataPoints: 100, - interval: null, - cacheTimeout: null, - format: 'none', - prefix: '', - postfix: '', - nullText: null, - valueMaps: [ - { - value: 'null', - op: '=', - text: 'N/A', +class SingleStat { + constructor(opts = {}) { + var defaults = { + id: generateGraphId(), + title: 'single stat', + targets: [], + error: false, + span: 12, + editable: true, + type: 'singlestat', + links: [], + maxDataPoints: 100, + interval: null, + cacheTimeout: null, + format: 'none', + prefix: '', + postfix: '', + nullText: null, + valueMaps: [ + { + value: 'null', + op: '=', + text: 'N/A', + }, + ], + nullPointMode: 'connected', + valueName: 'current', + prefixFontSize: '50%', + valueFontSize: '80%', + postfixFontSize: '50%', + thresholds: '', + colorBackground: false, + colorValue: false, + colors: [ + 'rgba(71, 212, 59, 0.4)', + 'rgba(245, 150, 40, 0.73)', + 'rgba(225, 40, 40, 0.59)', + ], + sparkline: { + show: true, + full: true, + lineColor: 'rgb(31, 193, 58)', + fillColor: 'rgba(134, 178, 214, 0.41)', }, - ], - nullPointMode: 'connected', - valueName: 'current', - prefixFontSize: '50%', - valueFontSize: '80%', - postfixFontSize: '50%', - thresholds: '', - colorBackground: false, - colorValue: false, - colors: [ - 'rgba(71, 212, 59, 0.4)', - 'rgba(245, 150, 40, 0.73)', - 'rgba(225, 40, 40, 0.59)', - ], - sparkline: { - show: true, - full: true, - lineColor: 'rgb(31, 193, 58)', - fillColor: 'rgba(134, 178, 214, 0.41)', - }, - datasource: 'graphite', - }; - this.state = defaults; - - // Overwrite defaults with custom values - Object.keys(opts).forEach(function eachOpt(opt) { - self.state[opt] = opts[opt]; - }); + datasource: 'graphite', + }; + this.state = defaults; - if (opts.targets) { - this.state.targets = []; - opts.targets.forEach(function addT(target) { - self.addTarget(target); + // Overwrite defaults with custom values + Object.keys(opts).forEach((opt) => { + this.state[opt] = opts[opt]; }); - } - // finally add to row/dashboard if given - if (opts.row && opts.dashboard) { - opts.row.addPanel(this); - opts.dashboard.addRow(opts.row); + if (opts.targets) { + this.state.targets = []; + opts.targets.forEach((target) => { + this.addTarget(target); + }); + } + + // finally add to row/dashboard if given + if (opts.row && opts.dashboard) { + opts.row.addPanel(this); + opts.dashboard.addRow(opts.row); + } } -} -SingleStat.prototype.generate = function generate() { - return this.state; -}; + generate() { + return this.state; + } -SingleStat.prototype.setTitle = function setTitle(title) { - this.state.title = title; -}; + setTitle(title) { + this.state.title = title; + } -SingleStat.prototype.addTarget = function addTarget(target) { - this.state.targets.push({ - target: target.toString(), - }); -}; + addTarget(target) { + this.state.targets.push({ + target: target.toString(), + }); + } +} module.exports = SingleStat; diff --git a/src/panels/table.js b/src/panels/table.js index 949c799..48de96d 100644 --- a/src/panels/table.js +++ b/src/panels/table.js @@ -22,89 +22,89 @@ var generateGraphId = require('../id'); -function Table(opts) { - opts = opts || {}; - var self = this; - - var defaults = { - title: 'Panel Title', - error: false, - span: 12, - editable: true, - type: 'table', - isNew: true, - id: generateGraphId(), - styles: [ - { - type: 'date', - pattern: 'Time', - dateFormat: 'YYYY-MM-DD HH:mm:ss', - }, - { - unit: 'short', - type: 'number', - decimals: 0, - colors: [ - 'rgba(245, 54, 54, 0.9)', - 'rgba(237, 129, 40, 0.89)', - 'rgba(50, 172, 45, 0.97)', - ], - colorMode: null, - pattern: '/.*/', - thresholds: [], - }, - ], - targets: [], - transform: 'timeseries_aggregations', - pageSize: null, - showHeader: true, - columns: [ - { - text: 'Avg', - value: 'avg', +class Table { + constructor(opts = {}) { + var defaults = { + title: 'Panel Title', + error: false, + span: 12, + editable: true, + type: 'table', + isNew: true, + id: generateGraphId(), + styles: [ + { + type: 'date', + pattern: 'Time', + dateFormat: 'YYYY-MM-DD HH:mm:ss', + }, + { + unit: 'short', + type: 'number', + decimals: 0, + colors: [ + 'rgba(245, 54, 54, 0.9)', + 'rgba(237, 129, 40, 0.89)', + 'rgba(50, 172, 45, 0.97)', + ], + colorMode: null, + pattern: '/.*/', + thresholds: [], + }, + ], + targets: [], + transform: 'timeseries_aggregations', + pageSize: null, + showHeader: true, + columns: [ + { + text: 'Avg', + value: 'avg', + }, + ], + scroll: true, + fontSize: '100%', + sort: { + col: 0, + desc: true, }, - ], - scroll: true, - fontSize: '100%', - sort: { - col: 0, - desc: true, - }, - links: [], - }; - this.state = defaults; + links: [], + }; + this.state = defaults; - // Overwrite defaults with custom values - Object.keys(opts).forEach(function eachOpt(opt) { - self.state[opt] = opts[opt]; - }); - - if (opts.targets) { - this.state.targets = []; - opts.targets.forEach(function addT(target) { - self.addTarget(target); + // Overwrite defaults with custom values + Object.keys(opts).forEach((opt) => { + this.state[opt] = opts[opt]; }); + + if (opts.targets) { + this.state.targets = []; + opts.targets.forEach((target) => { + this.addTarget(target); + }); + } + + // finally add to row/dashboard if given + if (opts.row && opts.dashboard) { + opts.row.addPanel(this); + opts.dashboard.addRow(opts.row); + } } - // finally add to row/dashboard if given - if (opts.row && opts.dashboard) { - opts.row.addPanel(this); - opts.dashboard.addRow(opts.row); + generate() { + return this.state; } -} -Table.prototype.generate = function generate() { - return this.state; -}; + setTitle(title) { + this.state.title = title; + } -Table.prototype.setTitle = function setTitle(title) { - this.state.title = title; -}; + addTarget(target) { + this.state.targets.push({ + target: target.toString(), + hide: target.hide, + }); + } +} -Table.prototype.addTarget = function addTarget(target) { - this.state.targets.push({ - target: target.toString(), - hide: target.hide, - }); -}; module.exports = Table; diff --git a/src/panels/text.js b/src/panels/text.js index 003e84b..233f9a6 100644 --- a/src/panels/text.js +++ b/src/panels/text.js @@ -22,42 +22,41 @@ var generateGraphId = require('../id'); -function Text(opts) { - opts = opts || {}; - var self = this; - - var defaults = { - title: '', - id: generateGraphId(), - error: false, - span: 12, - editable: true, - type: 'text', - mode: 'markdown', - content: '', - style: {}, - links: [], - }; - this.state = defaults; - - // Overwrite defaults with custom values - Object.keys(opts).forEach(function eachOpt(opt) { - self.state[opt] = opts[opt]; - }); - - // finally add to row/dashboard if given - if (opts.row && opts.dashboard) { - opts.row.addPanel(this); - opts.dashboard.addRow(opts.row); +class Text { + constructor(opts = {}) { + var defaults = { + title: '', + id: generateGraphId(), + error: false, + span: 12, + editable: true, + type: 'text', + mode: 'markdown', + content: '', + style: {}, + links: [], + }; + this.state = defaults; + + // Overwrite defaults with custom values + Object.keys(opts).forEach((opt) => { + this.state[opt] = opts[opt]; + }); + + // finally add to row/dashboard if given + if (opts.row && opts.dashboard) { + opts.row.addPanel(this); + opts.dashboard.addRow(opts.row); + } } -} -Text.prototype.generate = function generate() { - return this.state; -}; + generate() { + return this.state; + } -Text.prototype.setTitle = function setTitle(title) { - this.state.title = title; -}; + setTitle(title) { + this.state.title = title; + } +} module.exports = Text; diff --git a/src/publish.js b/src/publish.js index 409510d..f3fb5ad 100644 --- a/src/publish.js +++ b/src/publish.js @@ -23,9 +23,7 @@ const fetch = require('node-fetch'); const config = require('./config'); const errors = require('./errors'); -function publish(dashboard, opts) { - opts = opts || {}; - +function publish(dashboard, opts = {}) { if (!dashboard) { throw errors.UnfulfilledRequirement.create( '{component} missing requirement: {unfulfilledArg}', diff --git a/src/row.js b/src/row.js index 7b660e6..3052c42 100644 --- a/src/row.js +++ b/src/row.js @@ -22,41 +22,36 @@ var xtend = require('xtend'); -function Row(opts) { - opts = opts || {}; - var self = this; - - var state = { - title: 'New row', - height: '250px', - editable: true, - collapse: false, - panels: [], - showTitle: true, - }; - - this.state = xtend(state, opts); - this.panels = []; - - if (opts.panels) { - opts.panels.forEach(function addP(panel) { - self.addPanel(panel); - }); +class Row { + constructor(opts) { + opts = opts || {}; + var state = { + title: 'New row', + height: '250px', + editable: true, + collapse: false, + panels: [], + showTitle: true, + }; + + this.state = xtend(state, opts); + this.panels = []; + + if (opts.panels) { + opts.panels.forEach((panel) => { + this.addPanel(panel); + }); + } } -} - -Row.prototype.generate = function generate() { - var generatedJson = []; - this.panels.forEach(function generatePanelJson(panel) { - generatedJson.push(panel.generate()); - }); - this.state.panels = generatedJson; - return this.state; -}; + generate() { + this.state.panels = this.panels.map((panel) => panel.generate()); + return this.state; + } -Row.prototype.addPanel = function addPanel(panel) { - this.panels.push(panel); -}; + addPanel(panel) { + this.panels.push(panel); + } +} module.exports = Row; diff --git a/src/target.js b/src/target.js index 5db8e32..7a54954 100644 --- a/src/target.js +++ b/src/target.js @@ -23,46 +23,75 @@ var _ = require('underscore'); var util = require('util'); -function Target() { - if (arguments.length === 0) { - throw new Error( - 'Incorrect invocation of Target. ' + - 'Must provide at least one argument' - ); +class Target { + constructor() { + if (arguments.length === 0) { + throw new Error( + 'Incorrect invocation of Target. ' + + 'Must provide at least one argument' + ); + } + if (typeof arguments[0] === 'string') { + // Format string + this.source = util.format.apply(null, arguments); + } else { + // Another target + this.source = arguments[0]; + this.func = arguments[1]; + } } - if (typeof arguments[0] === 'string') { - // Format string - this.source = util.format.apply(null, arguments); - } else { - // Another target - this.source = arguments[0]; - this.func = arguments[1]; + + toString() { + if (this.func) { + const args = _.reduce( + this.func.slice(1), + function reduce(memo, arg) { + if (typeof arg === 'string') { + arg = JSON.stringify(arg); + } else { + arg = arg.toString(); + } + return memo + ', ' + arg; + }, + '' + ); + return this.func[0] + '(' + this.source.toString() + args + ')'; + } else { + return this.source; + } } -} -Target.prototype.toString = function toString() { - if (this.func) { - var args = _.reduce( - this.func.slice(1), - function reduce(memo, arg) { - if (typeof arg === 'string') { - arg = JSON.stringify(arg); - } else { - arg = arg.toString(); - } - return memo + ', ' + arg; - }, - '' - ); - return this.func[0] + '(' + this.source.toString() + args + ')'; - } else { - return this.source; + // Target Helpers + + cpu() { + return this.derivative().scale(0.016666666667).removeBelowValue(0); + } + + reallyFaded() { + return this.lineWidth(5).alpha(0.5); + } + + faded() { + return this.alpha(0.5).lineWidth(5); + } + + lastWeek() { + return this.timeShift('7d'); + } + + summarize15min() { + return this.summarize('15min'); } -}; + + hide() { + this.hide = true; + return this; + } +} // Primitive methods // Method Name: arity ignoring first target input -Target.PRIMITIVES = { +const PRIMITIVES = { absolute: 0, aggregateLine: 0, alias: 1, @@ -155,12 +184,15 @@ Target.PRIMITIVES = { useSeriesAbove: 3, weightedAverage: 2, }; +Target.PRIMITIVES = PRIMITIVES; _.each(Target.PRIMITIVES, function each(n, method) { Target.prototype[method] = function t() { if (arguments.length < n) { - console.warn('Incorrect number of arguments passed to %s', method); + /*eslint-disable*/ + console.warn("Incorrect number of arguments passed to %s", method); console.trace(); + /*eslint-enable*/ } return new Target( this, @@ -169,7 +201,7 @@ _.each(Target.PRIMITIVES, function each(n, method) { }; }); -Target.COLORS = [ +const COLORS = [ 'orange', 'blue', 'green', @@ -182,37 +214,12 @@ Target.COLORS = [ 'aqua', ]; +Target.COLORS = COLORS; + _.each(Target.COLORS, function each(color) { Target.prototype[color] = function t() { return this.color(color); }; }); -// Target Helpers - -Target.prototype.cpu = function cpu() { - return this.derivative().scale(0.016666666667).removeBelowValue(0); -}; - -Target.prototype.reallyFaded = function reallyFaded() { - return this.lineWidth(5).alpha(0.5); -}; - -Target.prototype.faded = function faded() { - return this.alpha(0.5).lineWidth(5); -}; - -Target.prototype.lastWeek = function lastWeek() { - return this.timeShift('7d'); -}; - -Target.prototype.summarize15min = function summarize15min() { - return this.summarize('15min'); -}; - -Target.prototype.hide = function hide() { - this.hide = true; - return this; -}; - module.exports = Target; diff --git a/src/templates/custom.js b/src/templates/custom.js index f8b0ceb..15e934c 100644 --- a/src/templates/custom.js +++ b/src/templates/custom.js @@ -22,96 +22,100 @@ const DEFAULT_VARIABLE_ALL = '$__all'; -function Custom(opts) { - opts = opts || {}; - this.state = { - allFormat: 'glob', - current: {}, - datasource: null, - includeAll: false, - allValue: '', - name: 'template', - options: [], - query: null, - refresh: 0, - refresh_on_load: false, - type: 'custom', - }; - this.defaultValue = ''; +class Custom { + constructor(opts = {}) { + this.state = { + allFormat: 'glob', + current: {}, + datasource: null, + includeAll: false, + allValue: '', + name: 'template', + options: [], + query: null, + refresh: 0, + refresh_on_load: false, + type: 'custom', + }; + this.defaultValue = ''; - // Overwrite defaults with custom values - Object.keys(opts).forEach((key) => { - switch (key) { - case 'defaultValue': - this.defaultValue = opts[key]; - break; - default: - this.state[key] = opts[key]; - } - }); - this._processOptions(); -} + // Overwrite defaults with custom values + Object.keys(opts).forEach((key) => { + switch (key) { + case 'defaultValue': + this.defaultValue = opts[key]; + break; + default: + this.state[key] = opts[key]; + } + }); + this._processOptions(); + } -/* - * Ensures options are objects, and updates the state's query and current - * values. - */ -Custom.prototype._processOptions = function _processOptions() { - if (!this.state.options.length) { - if (this.defaultValue !== '') { - throw new SyntaxError( - 'cannot define default value without any options' - ); + /* + * Ensures options are objects, and updates the state's query and current + * values. + */ + _processOptions() { + if (!this.state.options.length) { + if (this.defaultValue !== '') { + throw new SyntaxError( + 'cannot define default value without any options' + ); + } + return; } - return; - } - let newOptions = []; - let newQuery = []; + let newOptions = []; + let newQuery = []; - let hasAll = false; - for (let i = 0; i < this.state.options.length; i++) { - const option = this.state.options[i]; - const isObject = - typeof option === 'object' && option.constructor === Object; - const opt = isObject - ? option - : { - text: option, - value: option, - }; - if (opt.value === DEFAULT_VARIABLE_ALL) { - if (hasAll) { - continue; + let hasAll = false; + for (let i = 0; i < this.state.options.length; i++) { + const option = this.state.options[i]; + const isObject = + typeof option === 'object' && option.constructor === Object; + const opt = isObject + ? option + : { + text: option, + value: option, + }; + if (opt.value === DEFAULT_VARIABLE_ALL) { + if (hasAll) { + continue; + } + hasAll = true; } - hasAll = true; - } - newOptions.push(opt); - newQuery.push(opt.value); - } + newOptions.push(opt); + newQuery.push(opt.value); + } - if (this.defaultValue !== '') { - const defaultOption = newOptions.find( - (option) => option.value === this.defaultValue - ); - if (!defaultOption) { - throw new SyntaxError('default value not found in options list'); + if (this.defaultValue !== '') { + const defaultOption = newOptions.find( + (option) => option.value === this.defaultValue + ); + if (!defaultOption) { + throw new SyntaxError( + 'default value not found in options list' + ); + } + this.state.current = defaultOption; + } else if ( + (!this.state.current || + Object.keys(this.state.current).length === 0) && + !this.state.includeAll + ) { + this.state.current = newOptions[0]; } - this.state.current = defaultOption; - } else if ( - (!this.state.current || Object.keys(this.state.current).length === 0) && - !this.state.includeAll - ) { - this.state.current = newOptions[0]; - } - this.state.options = newOptions; - this.state.query = newQuery.join(','); -}; + this.state.options = newOptions; + this.state.query = newQuery.join(','); + } -Custom.prototype.generate = function generate() { - return this.state; -}; + generate() { + return this.state; + } +} module.exports = Custom; diff --git a/src/templates/query.js b/src/templates/query.js index 947ece0..406f9c2 100644 --- a/src/templates/query.js +++ b/src/templates/query.js @@ -39,57 +39,56 @@ * * @see http://docs.grafana.org/reference/templating/ */ -function Query(query, opts) { - opts = opts || {}; - var self = this; +class Query { + constructor(query, opts = {}) { + this.state = { + query: query, + name: opts.name, + datasource: opts.datasource, + type: 'query', + includeAll: true, + allFormat: 'wildcard', + allValue: null, + refresh: false, + multi: false, + options: [], + current: {}, + }; - this.state = { - query: query, - name: opts.name, - datasource: opts.datasource, - type: 'query', - includeAll: true, - allFormat: 'wildcard', - allValue: null, - refresh: false, - multi: false, - options: [], - current: {}, - }; + this._required = ['name', 'datasource']; - this._required = ['name', 'datasource']; + this._overridable = [ + 'includeAll', + 'allFormat', + 'allValue', + 'multi', + 'multiFormat', + 'refresh', + 'regex', + 'tag', + ]; - this._overridable = [ - 'includeAll', - 'allFormat', - 'allValue', - 'multi', - 'multiFormat', - 'refresh', - 'regex', - 'tag', - ]; + // Override overridable values + Object.keys(opts).forEach((opt) => { + if (this._overridable.indexOf(opt) !== -1) { + this.state[opt] = opts[opt]; + } + }); - // Override overridable values - Object.keys(opts).forEach(function eachOpt(opt) { - if (self._overridable.indexOf(opt) !== -1) { - self.state[opt] = opts[opt]; - } - }); + // assert required state has been populated + this._required.forEach((reqOpt) => { + if (!this.state[reqOpt]) { + throw new Error('Missing Requirement: ' + reqOpt); + } + }); - // assert required state has been populated - this._required.forEach(function eachRequired(reqOpt) { - if (!self.state[reqOpt]) { - throw new Error('Missing Requirement: ' + reqOpt); - } - }); + // make state immutable after this point + Object.freeze(this.state); + } - // make state immutable after this point - Object.freeze(this.state); + generate() { + return this.state; + } } -Query.prototype.generate = function generate() { - return this.state; -}; - module.exports = Query;