Commit 80f1ea7e authored by Lukas Eipert's avatar Lukas Eipert

Run prettier on 31 files - 20 of 73

Part of our prettier migration; changing the arrow-parens style.
parent 0e6e345f
......@@ -517,39 +517,6 @@ app/assets/javascripts/lib/utils/text_markdown.js
app/assets/javascripts/lib/utils/text_utility.js
app/assets/javascripts/lib/utils/type_utility.js
## inspiring-lovelace
app/assets/javascripts/mini_pipeline_graph_dropdown.js
app/assets/javascripts/mirrors/mirror_repos.js
app/assets/javascripts/mirrors/ssh_mirror.js
app/assets/javascripts/monitoring/components/alert_widget.vue
app/assets/javascripts/monitoring/components/alert_widget_form.vue
app/assets/javascripts/monitoring/components/charts/annotations.js
app/assets/javascripts/monitoring/components/charts/anomaly.vue
app/assets/javascripts/monitoring/components/charts/bar.vue
app/assets/javascripts/monitoring/components/charts/column.vue
app/assets/javascripts/monitoring/components/charts/heatmap.vue
app/assets/javascripts/monitoring/components/charts/options.js
app/assets/javascripts/monitoring/components/charts/stacked_column.vue
app/assets/javascripts/monitoring/components/charts/time_series.vue
app/assets/javascripts/monitoring/components/dashboard_panel.vue
app/assets/javascripts/monitoring/components/duplicate_dashboard_form.vue
app/assets/javascripts/monitoring/components/duplicate_dashboard_modal.vue
app/assets/javascripts/monitoring/components/embeds/embed_group.vue
app/assets/javascripts/monitoring/components/embeds/metric_embed.vue
app/assets/javascripts/monitoring/components/empty_state.vue
app/assets/javascripts/monitoring/components/variables/dropdown_field.vue
app/assets/javascripts/monitoring/csv_export.js
app/assets/javascripts/monitoring/requests/index.js
app/assets/javascripts/monitoring/services/alerts_service.js
app/assets/javascripts/monitoring/stores/embed_group/getters.js
app/assets/javascripts/monitoring/stores/mutations.js
app/assets/javascripts/monitoring/stores/utils.js
app/assets/javascripts/monitoring/stores/variable_mapping.js
app/assets/javascripts/monitoring/utils.js
app/assets/javascripts/monitoring/validators.js
app/assets/javascripts/mr_notes/init_notes.js
app/assets/javascripts/mr_notes/stores/getters.js
## cool-dirac
app/assets/javascripts/mr_popover/components/mr_popover.vue
app/assets/javascripts/mr_popover/index.js
......
......@@ -47,7 +47,7 @@ export default class MiniPipelineGraph {
$(document).on(
'click',
`${this.container} .js-builds-dropdown-list a.mini-pipeline-graph-dropdown-item`,
e => {
(e) => {
e.stopPropagation();
},
);
......
......@@ -80,7 +80,7 @@ export default class MirrorRepos {
this.debouncedUpdateUrl = debounce(() => this.updateUrl(), 200);
this.$urlInput.on('input', () => this.debouncedUpdateUrl());
this.$protectedBranchesInput.on('change', () => this.updateProtectedBranches());
this.$table.on('click', '.js-delete-mirror', event => this.deleteMirror(event));
this.$table.on('click', '.js-delete-mirror', (event) => this.deleteMirror(event));
}
togglePassword() {
......
......@@ -29,10 +29,10 @@ export default class SSHMirror {
this.handleRepositoryUrlInput(true);
this.$repositoryUrl.on('keyup', () => this.handleRepositoryUrlInput());
this.$knownHosts.on('keyup', e => this.handleSSHKnownHostsInput(e));
this.$dropdownAuthType.on('change', e => this.handleAuthTypeChange(e));
this.$btnDetectHostKeys.on('click', e => this.handleDetectHostKeys(e));
this.$btnSSHHostsShowAdvanced.on('click', e => this.handleSSHHostsAdvanced(e));
this.$knownHosts.on('keyup', (e) => this.handleSSHKnownHostsInput(e));
this.$dropdownAuthType.on('change', (e) => this.handleAuthTypeChange(e));
this.$btnDetectHostKeys.on('click', (e) => this.handleDetectHostKeys(e));
this.$btnSSHHostsShowAdvanced.on('click', (e) => this.handleSSHHostsAdvanced(e));
}
/**
......@@ -100,7 +100,7 @@ export default class SSHMirror {
})
.catch(stop);
})
.then(res => {
.then((res) => {
$btnLoadSpinner.addClass('d-none');
// Once data is received, we show verification info along with Host keys and fingerprints
this.$hostKeysInformation
......@@ -160,7 +160,7 @@ export default class SSHMirror {
showSSHInformation(sshHostKeys) {
const $fingerprintsList = this.$hostKeysInformation.find('.js-fingerprints-list');
let fingerprints = '';
sshHostKeys.fingerprints.forEach(fingerprint => {
sshHostKeys.fingerprints.forEach((fingerprint) => {
const escFingerprints = escape(fingerprint.fingerprint);
fingerprints += `<code>${escFingerprints}</code>`;
});
......
......@@ -97,12 +97,12 @@ export default {
return Boolean(this.firingAlerts.length);
},
firingAlerts() {
return values(this.alertsToManage).filter(alert =>
return values(this.alertsToManage).filter((alert) =>
this.passedAlertThreshold(this.getQueryData(alert), alert),
);
},
formattedFiringAlerts() {
return this.firingAlerts.map(alert => this.formatAlertSummary(alert.alert_path));
return this.firingAlerts.map((alert) => this.formatAlertSummary(alert.alert_path));
},
configuredAlert() {
return this.hasAlerts ? values(this.alertsToManage)[0].metricId : '';
......@@ -116,13 +116,13 @@ export default {
fetchAlertData() {
this.isLoading = true;
const queriesWithAlerts = this.relevantQueries.filter(query => query.alert_path);
const queriesWithAlerts = this.relevantQueries.filter((query) => query.alert_path);
return Promise.all(
queriesWithAlerts.map(query =>
queriesWithAlerts.map((query) =>
this.service
.readAlert(query.alert_path)
.then(alertAttributes => this.setAlert(alertAttributes, query.metricId)),
.then((alertAttributes) => this.setAlert(alertAttributes, query.metricId)),
),
)
.then(() => {
......@@ -141,7 +141,7 @@ export default {
},
formatAlertSummary(alertPath) {
const alert = this.alertsToManage[alertPath];
const alertQuery = this.relevantQueries.find(query => query.metricId === alert.metricId);
const alertQuery = this.relevantQueries.find((query) => query.metricId === alert.metricId);
return `${alertQuery.label} ${alert.operator} ${alert.threshold}`;
},
......@@ -150,19 +150,19 @@ export default {
switch (operator) {
case OPERATORS.greaterThan:
return data.some(value => value > threshold);
return data.some((value) => value > threshold);
case OPERATORS.lessThan:
return data.some(value => value < threshold);
return data.some((value) => value < threshold);
case OPERATORS.equalTo:
return data.some(value => value === threshold);
return data.some((value) => value === threshold);
default:
return false;
}
},
getQueryData(alert) {
const alertQuery = this.relevantQueries.find(query => query.metricId === alert.metricId);
const alertQuery = this.relevantQueries.find((query) => query.metricId === alert.metricId);
return get(alertQuery, 'result[0].values', []).map(value => get(value, '[1]', null));
return get(alertQuery, 'result[0].values', []).map((value) => get(value, '[1]', null));
},
showModal() {
this.$root.$emit('bv::show::modal', this.modalId);
......@@ -179,7 +179,7 @@ export default {
this.isLoading = true;
this.service
.createAlert(newAlert)
.then(alertAttributes => {
.then((alertAttributes) => {
this.setAlert(alertAttributes, prometheus_metric_id);
this.isLoading = false;
this.hideModal();
......@@ -194,7 +194,7 @@ export default {
this.isLoading = true;
this.service
.updateAlert(alert, updatedAlert)
.then(alertAttributes => {
.then((alertAttributes) => {
this.setAlert(alertAttributes, this.alertsToManage[alert].metricId);
this.isLoading = false;
this.hideModal();
......
......@@ -99,7 +99,7 @@ export default {
return this.alertQuery.length ? true : null;
},
currentQuery() {
return this.relevantQueries.find(query => query.metricId === this.prometheusMetricId) || {};
return this.relevantQueries.find((query) => query.metricId === this.prometheusMetricId) || {};
},
formDisabled() {
// We need a prometheusMetricId to determine whether we're
......@@ -151,7 +151,7 @@ export default {
},
methods: {
selectQuery(queryId) {
const existingAlertPath = findKey(this.alertsToManage, alert => alert.metricId === queryId);
const existingAlertPath = findKey(this.alertsToManage, (alert) => alert.metricId === queryId);
const existingAlert = this.alertsToManage[existingAlertPath];
if (existingAlert) {
......
......@@ -52,7 +52,7 @@ export const annotationsYAxis = {
* @param {Object} annotation object
* @returns {Object} markLine object
*/
export const parseAnnotations = annotations =>
export const parseAnnotations = (annotations) =>
annotations.reduce(
(acc, annotation) => {
acc.lines.push({
......@@ -87,7 +87,7 @@ export const parseAnnotations = annotations =>
*/
export const generateAnnotationsSeries = ({ deployments = [], annotations = [] } = {}) => {
// deployment data points
const data = deployments.map(deployment => {
const data = deployments.map((deployment) => {
return {
name: 'deployments',
value: [deployment.createdAt, annotationsYAxisCoords.pos],
......
......@@ -62,7 +62,7 @@ export default {
},
computed: {
series() {
return this.graphData.metrics.map(metric => {
return this.graphData.metrics.map((metric) => {
const values = metric.result && metric.result[0] ? metric.result[0].values : [];
return {
label: metric.label,
......@@ -78,14 +78,14 @@ export default {
* This offset is the lowest value.
*/
yOffset() {
const values = flattenDeep(this.series.map(ser => ser.data.map(([, y]) => y)));
const values = flattenDeep(this.series.map((ser) => ser.data.map(([, y]) => y)));
const min = values.length ? Math.floor(Math.min(...values)) : 0;
return min < 0 ? -min : 0;
},
metricData() {
const originalMetricQuery = this.graphData.metrics[0];
const metricQuery = produce(originalMetricQuery, draftQuery => {
const metricQuery = produce(originalMetricQuery, (draftQuery) => {
// eslint-disable-next-line no-param-reassign
draftQuery.result[0].values = draftQuery.result[0].values.map(([x, y]) => [
x,
......@@ -112,7 +112,7 @@ export default {
},
showSymbol: true,
itemStyle: {
color: params => {
color: (params) => {
if (this.isDatapointAnomaly(params.dataIndex)) {
return colorValues.anomalySymbol;
}
......@@ -131,7 +131,7 @@ export default {
const yAxisWithOffset = {
axisLabel: {
formatter: num => roundOffFloat(num - this.yOffset, 3).toString(),
formatter: (num) => roundOffFloat(num - this.yOffset, 3).toString(),
},
};
......@@ -156,7 +156,7 @@ export default {
boundarySeries.push(
this.makeBoundarySeries({
name: this.formatLegendLabel(upperSeries),
data: calcOffsetY(upperSeries.data, i => -this.yValue(LOWER, i)),
data: calcOffsetY(upperSeries.data, (i) => -this.yValue(LOWER, i)),
areaStyle: {
color: AREA_COLOR,
opacity: AREA_OPACITY,
......
......@@ -67,12 +67,12 @@ export default {
},
setSvg(name) {
getSvgIconPathContent(name)
.then(path => {
.then((path) => {
if (path) {
this.$set(this.svgs, name, `path://${path}`);
}
})
.catch(e => {
.catch((e) => {
// eslint-disable-next-line no-console, @gitlab/require-i18n-strings
console.error('SVG could not be rendered correctly: ', e);
});
......
......@@ -90,7 +90,7 @@ export default {
},
setSvg(name) {
getSvgIconPathContent(name)
.then(path => {
.then((path) => {
if (path) {
this.$set(this.svgs, name, `path://${path}`);
}
......
......@@ -42,10 +42,10 @@ export default {
return this.graphData.y_label || '';
},
xAxisLabels() {
return this.metrics.result.map(res => Object.values(res.metric)[0]);
return this.metrics.result.map((res) => Object.values(res.metric)[0]);
},
yAxisLabels() {
return this.result.values.map(val => {
return this.result.values.map((val) => {
const [yLabel] = val;
return formatDate(new Date(yLabel), {
......
......@@ -51,7 +51,7 @@ const getDataAxisOptions = ({ format, precision, name }) => {
nameLocation: 'center', // same as gitlab-ui's default
scale: true,
axisLabel: {
formatter: val => formatter(val, precision, maxDataAxisTickLength),
formatter: (val) => formatter(val, precision, maxDataAxisTickLength),
},
};
};
......@@ -85,7 +85,7 @@ export const getTimeAxisOptions = ({
name: __('Time'),
type: axisTypes.time,
axisLabel: {
formatter: date => formatDate(date, { format, timezone }),
formatter: (date) => formatDate(date, { format, timezone }),
},
axisPointer: {
snap: false,
......@@ -109,7 +109,7 @@ export const getTooltipFormatter = ({
precision = defaultTooltipPrecision,
} = {}) => {
const formatter = getFormatter(format);
return num => formatter(num, precision);
return (num) => formatter(num, precision);
};
// Thresholds
......@@ -138,9 +138,9 @@ export const getValidThresholds = ({ mode, range = {}, values = [] } = {}) => {
const uniqueThresholds = uniq(values);
const numberThresholds = uniqueThresholds.filter(threshold => isFinite(threshold));
const numberThresholds = uniqueThresholds.filter((threshold) => isFinite(threshold));
const validThresholds = numberThresholds.filter(threshold => {
const validThresholds = numberThresholds.filter((threshold) => {
let isValid;
if (mode === thresholdModeTypes.PERCENTAGE) {
......@@ -152,7 +152,7 @@ export const getValidThresholds = ({ mode, range = {}, values = [] } = {}) => {
return isValid;
});
const transformedThresholds = validThresholds.map(threshold => {
const transformedThresholds = validThresholds.map((threshold) => {
let transformedThreshold;
if (mode === 'percentage') {
......
......@@ -68,7 +68,7 @@ export default {
if (!result || result.length === 0) {
return [];
}
return { name, data: result[0].values.map(val => val[1]) };
return { name, data: result[0].values.map((val) => val[1]) };
})
.slice(0, 1);
},
......@@ -89,7 +89,7 @@ export default {
if (!result || result.length === 0) {
return [];
}
return result[0].values.map(val => val[0]);
return result[0].values.map((val) => val[0]);
},
dataZoomConfig() {
const handleIcon = this.svgs['scroll-handle'];
......@@ -106,7 +106,7 @@ export default {
};
},
seriesNames() {
return this.graphData.metrics.map(metric => metric.label);
return this.graphData.metrics.map((metric) => metric.label);
},
},
created() {
......@@ -115,12 +115,12 @@ export default {
methods: {
setSvg(name) {
getSvgIconPathContent(name)
.then(path => {
.then((path) => {
if (path) {
this.$set(this.svgs, name, `path://${path}`);
}
})
.catch(e => {
.catch((e) => {
// eslint-disable-next-line no-console, @gitlab/require-i18n-strings
console.error('SVG could not be rendered correctly: ', e);
});
......
......@@ -11,7 +11,7 @@ import { makeDataSeries } from '~/helpers/monitor_helper';
import { graphDataValidatorForValues } from '../../utils';
import { formatDate, timezones } from '../../format_date';
export const timestampToISODate = timestamp => new Date(timestamp).toISOString();
export const timestampToISODate = (timestamp) => new Date(timestamp).toISOString();
const THROTTLED_DATAZOOM_WAIT = 1000; // milliseconds
......@@ -304,7 +304,7 @@ export default {
this.tooltip.content = [];
params.seriesData.forEach(dataPoint => {
params.seriesData.forEach((dataPoint) => {
if (dataPoint.value) {
const [, yVal] = dataPoint.value;
this.tooltip.type = dataPoint.name;
......@@ -327,12 +327,12 @@ export default {
},
setSvg(name) {
getSvgIconPathContent(name)
.then(path => {
.then((path) => {
if (path) {
this.$set(this.svgs, name, `path://${path}`);
}
})
.catch(e => {
.catch((e) => {
// eslint-disable-next-line no-console, @gitlab/require-i18n-strings
console.error('SVG could not be rendered correctly: ', e);
});
......
......@@ -271,8 +271,8 @@ export default {
methods: {
getGraphAlerts(queries) {
if (!this.allAlerts) return {};
const metricIdsForChart = queries.map(q => q.metricId);
return pickBy(this.allAlerts, alert => metricIdsForChart.includes(alert.metricId));
const metricIdsForChart = queries.map((q) => q.metricId);
return pickBy(this.allAlerts, (alert) => metricIdsForChart.includes(alert.metricId));
},
getGraphAlertValues(queries) {
return Object.values(this.getGraphAlerts(queries));
......@@ -346,10 +346,10 @@ export default {
}
},
getAlertRunbooks(queries) {
const hasRunbook = alert => Boolean(alert.runbookUrl);
const hasRunbook = (alert) => Boolean(alert.runbookUrl);
const graphAlertsWithRunbooks = pickBy(this.getGraphAlerts(queries), hasRunbook);
const alertToRunbookTransform = alert => {
const alertQuery = queries.find(query => query.metricId === alert.metricId);
const alertToRunbookTransform = (alert) => {
const alertQuery = queries.find((query) => query.metricId === alert.metricId);
return {
key: alert.metricId,
href: alert.runbookUrl,
......
......@@ -3,7 +3,7 @@ import { GlFormGroup, GlFormInput, GlFormRadioGroup, GlFormTextarea } from '@git
import { escape as esc } from 'lodash';
import { __, s__, sprintf } from '~/locale';
const defaultFileName = dashboard => dashboard.path.split('/').reverse()[0];
const defaultFileName = (dashboard) => dashboard.path.split('/').reverse()[0];
export default {
components: {
......
......@@ -42,7 +42,7 @@ export default {
this.loading = true;
this.alert = null;
this.duplicateSystemDashboard(this.form)
.then(createdDashboard => {
.then((createdDashboard) => {
this.loading = false;
this.alert = null;
......@@ -55,7 +55,7 @@ export default {
this.form.branch === this.defaultBranch ? createdDashboard : this.selectedDashboard;
this.$emit(events.dashboardDuplicated, dashboard);
})
.catch(error => {
.catch((error) => {
this.loading = false;
this.alert = error;
});
......
......@@ -17,7 +17,7 @@ export default {
urls: {
type: Array,
required: true,
validator: urls => urls.length > 0,
validator: (urls) => urls.length > 0,
},
},
data() {
......
......@@ -101,7 +101,7 @@ export default {
},
}),
chartHasData(chart) {
return chart.metrics.some(metric => this.metricsWithData.includes(metric.metricId));
return chart.metrics.some((metric) => this.metricsWithData.includes(metric.metricId));
},
onSidebarMutation() {
setTimeout(() => {
......
......@@ -12,7 +12,7 @@ export default {
selectedState: {
type: String,
required: true,
validator: state => Object.values(dashboardEmptyStates).includes(state),
validator: (state) => Object.values(dashboardEmptyStates).includes(state),
},
documentationPath: {
type: String,
......
......@@ -28,7 +28,7 @@ export default {
},
computed: {
text() {
const selectedOpt = this.options.values?.find(opt => opt.value === this.value);
const selectedOpt = this.options.values?.find((opt) => opt.value === this.value);
return selectedOpt?.text || this.value;
},
},
......
......@@ -66,8 +66,8 @@ const csvMetricHeaders = (axisLabel, metrics) =>
*
* @param {Array} metrics - Metrics with results
*/
const csvMetricValues = metrics =>
metrics.flatMap(({ result }) => result.map(res => res.values || []));
const csvMetricValues = (metrics) =>
metrics.flatMap(({ result }) => result.map((res) => res.values || []));
/**
* Returns headers and rows for csv, sorted by their timestamp.
......@@ -99,7 +99,7 @@ const csvData = (metricHeaders, metricValues) => {
const rows = Object.keys(rowsByTimestamp)
.sort()
.map(timestamp => {
.map((timestamp) => {
// force each row to have the same number of entries
rowsByTimestamp[timestamp].length = metricHeaders.length;
// add timestamp as the first entry
......@@ -111,7 +111,7 @@ const csvData = (metricHeaders, metricValues) => {
// appearing inside a field must be escaped by preceding it with
// another double quote."
// https://tools.ietf.org/html/rfc4180#page-2
const headers = metricHeaders.map(header => `"${header.replace(/"/g, '""')}"`);
const headers = metricHeaders.map((header) => `"${header.replace(/"/g, '""')}"`);
return {
headers: ['timestamp', ...headers],
......@@ -125,12 +125,12 @@ const csvData = (metricHeaders, metricValues) => {
* @param {Object} graphData - Panel contents
* @returns {String}
*/
export const graphDataToCsv = graphData => {
export const graphDataToCsv = (graphData) => {
const delimiter = ',';
const br = '\r\n';
const { metrics = [], y_label: axisLabel } = graphData;
const metricsWithResults = metrics.filter(metric => metric.result);
const metricsWithResults = metrics.filter((metric) => metric.result);
const metricHeaders = csvMetricHeaders(axisLabel, metricsWithResults);
const metricValues = csvMetricValues(metricsWithResults);
const { headers, rows } = csvData(metricHeaders, metricValues);
......@@ -140,7 +140,7 @@ export const graphDataToCsv = graphData => {
}
const headerLine = headers.join(delimiter) + br;
const lines = rows.map(row => row.join(delimiter));
const lines = rows.map((row) => row.join(delimiter));
return headerLine + lines.join(br) + br;
};
......@@ -3,10 +3,10 @@ import statusCodes from '~/lib/utils/http_status';
import { backOff } from '~/lib/utils/common_utils';
import { PROMETHEUS_TIMEOUT } from '../constants';
const cancellableBackOffRequest = makeRequestCallback =>
const cancellableBackOffRequest = (makeRequestCallback) =>
backOff((next, stop) => {
makeRequestCallback()
.then(resp => {
.then((resp) => {
if (resp.status === statusCodes.NO_CONTENT) {
next();
} else {
......@@ -16,19 +16,19 @@ const cancellableBackOffRequest = makeRequestCallback =>
// If the request is cancelled by axios
// then consider it as noop so that its not
// caught by subsequent catches
.catch(thrown => (axios.isCancel(thrown) ? undefined : stop(thrown)));
.catch((thrown) => (axios.isCancel(thrown) ? undefined : stop(thrown)));
}, PROMETHEUS_TIMEOUT);
export const getDashboard = (dashboardEndpoint, params) =>
cancellableBackOffRequest(() => axios.get(dashboardEndpoint, { params })).then(
axiosResponse => axiosResponse.data,
(axiosResponse) => axiosResponse.data,
);
export const getPrometheusQueryData = (prometheusEndpoint, params, opts) =>
cancellableBackOffRequest(() => axios.get(prometheusEndpoint, { params, ...opts }))
.then(axiosResponse => axiosResponse.data)
.then(prometheusResponse => prometheusResponse.data)
.catch(error => {
.then((axiosResponse) => axiosResponse.data)
.then((prometheusResponse) => prometheusResponse.data)
.catch((error) => {
// Prometheus returns errors in specific cases
// https://prometheus.io/docs/prometheus/latest/querying/api/#format-overview
const { response = {} } = error;
......
......@@ -10,7 +10,7 @@ export default class AlertsService {
}
getAlerts() {
return axios.get(this.alertsEndpoint).then(resp => mapAlert(resp.data));
return axios.get(this.alertsEndpoint).then((resp) => mapAlert(resp.data));
}
createAlert({ prometheus_metric_id, operator, threshold, runbookUrl }) {
......@@ -21,23 +21,23 @@ export default class AlertsService {
threshold,
runbook_url: runbookUrl,
})
.then(resp => mapAlert(resp.data));
.then((resp) => mapAlert(resp.data));
}
// eslint-disable-next-line class-methods-use-this
readAlert(alertPath) {
return axios.get(alertPath).then(resp => mapAlert(resp.data));
return axios.get(alertPath).then((resp) => mapAlert(resp.data));
}
// eslint-disable-next-line class-methods-use-this
updateAlert(alertPath, { operator, threshold, runbookUrl }) {
return axios
.put(alertPath, { operator, threshold, runbook_url: runbookUrl })
.then(resp => mapAlert(resp.data));
.then((resp) => mapAlert(resp.data));
}
// eslint-disable-next-line class-methods-use-this
deleteAlert(alertPath) {
return axios.delete(alertPath).then(resp => resp.data);
return axios.delete(alertPath).then((resp) => resp.data);
}
}
export const metricsWithData = (state, getters, rootState, rootGetters) =>
state.modules.map(module => rootGetters[`${module}/metricsWithData`]().length);
state.modules.map((module) => rootGetters[`${module}/metricsWithData`]().length);
......@@ -15,9 +15,9 @@ import { optionsFromSeriesData } from './variable_mapping';
*/
const findMetricInDashboard = (metricId, dashboard) => {
let res = null;
dashboard.panelGroups.forEach(group => {
group.panels.forEach(panel => {
panel.metrics.forEach(metric => {
dashboard.panelGroups.forEach((group) => {
group.panels.forEach((panel) => {
panel.metrics.forEach((metric) => {
if (metric.metricId === metricId) {
res = metric;
}
......@@ -31,7 +31,7 @@ const findMetricInDashboard = (metricId, dashboard) => {
* Maps a backened error state to a `metricStates` constant
* @param {Object} error - Error from backend response
*/
const emptyStateFromError = error => {
const emptyStateFromError = (error) => {
if (!error) {
return metricStates.UNKNOWN_ERROR;
}
......@@ -53,7 +53,7 @@ const emptyStateFromError = error => {
return metricStates.UNKNOWN_ERROR;
};
export const metricStateFromData = data => {
export const metricStateFromData = (data) => {
if (data?.result?.length) {
const result = normalizeQueryResponseData(data);
return { state: metricStates.OK, result: Object.freeze(result) };
......@@ -93,7 +93,7 @@ export default {
state.isUpdatingStarredValue = true;
},
[types.RECEIVE_DASHBOARD_STARRING_SUCCESS](state, { selectedDashboard, newStarredValue }) {
const index = state.allDashboards.findIndex(d => d === selectedDashboard);
const index = state.allDashboards.findIndex((d) => d === selectedDashboard);
state.isUpdatingStarredValue = false;
......@@ -196,7 +196,7 @@ export default {
state.showErrorBanner = enabled;
},
[types.SET_PANEL_GROUP_METRICS](state, payload) {
const panelGroup = state.dashboard.panelGroups.find(pg => payload.key === pg.key);
const panelGroup = state.dashboard.panelGroups.find((pg) => payload.key === pg.key);
panelGroup.panels = payload.panels;
},
[types.SET_ENVIRONMENTS_FILTER](state, searchTerm) {
......@@ -207,7 +207,7 @@ export default {
state.expandedPanel.panel = panel;
},
[types.UPDATE_VARIABLE_VALUE](state, { name, value }) {
const variable = state.variables.find(v => v.name === name);
const variable = state.variables.find((v) => v.name === name);
if (variable) {
Object.assign(variable, {
value,
......
......@@ -40,7 +40,7 @@ export const uniqMetricsId = ({ metric_id, id }) => `${metric_id || NOT_IN_DB_PR
* @param {String} str String with leading slash
* @returns {String}
*/
export const removeLeadingSlash = str => (str || '').replace(/^\/+/, '');
export const removeLeadingSlash = (str) => (str || '').replace(/^\/+/, '');
/**
* GraphQL environments API returns only id and name.
......@@ -52,7 +52,7 @@ export const removeLeadingSlash = str => (str || '').replace(/^\/+/, '');
* @returns {Array}
*/
export const parseEnvironmentsResponse = (response = [], projectPath) =>
(response || []).map(env => {
(response || []).map((env) => {
const id = getIdFromGraphQLId(env.id);
return {
...env,
......@@ -75,11 +75,11 @@ export const parseEnvironmentsResponse = (response = [], projectPath) =>
* @param {Array} response annotations response
* @returns {Array} parsed responses
*/
export const parseAnnotationsResponse = response => {
export const parseAnnotationsResponse = (response) => {
if (!response) {
return [];
}
return response.map(annotation => ({
return response.map((annotation) => ({
...annotation,
startingAt: new Date(annotation.startingAt),
endingAt: annotation.endingAt ? new Date(annotation.endingAt) : null,
......@@ -99,7 +99,7 @@ export const parseAnnotationsResponse = response => {
* @param {Array} metrics - Array of prometheus metrics
* @returns {Object}
*/
const mapToMetricsViewModel = metrics =>
const mapToMetricsViewModel = (metrics) =>
metrics.map(({ label, id, metric_id, query_range, prometheus_endpoint_path, ...metric }) => ({
label,
queryRange: query_range,
......@@ -230,7 +230,7 @@ const mapToPanelGroupViewModel = ({ group = '', panels = [] }, i) => {
* @param {Object} timeRange
* @returns {Object}
*/
export const convertToGrafanaTimeRange = timeRange => {
export const convertToGrafanaTimeRange = (timeRange) => {
const timeRangeType = getRangeType(timeRange);
if (timeRangeType === DATETIME_RANGE_TYPES.fixed) {
return {
......@@ -272,7 +272,7 @@ export const convertTimeRanges = (timeRange, type) => {
* @param {Object} metadata
* @returns {Function}
*/
export const addDashboardMetaDataToLink = metadata => link => {
export const addDashboardMetaDataToLink = (metadata) => (link) => {
let modifiedLink = { ...link };
if (metadata.timeRange) {
modifiedLink = {
......@@ -307,7 +307,7 @@ export const mapToDashboardViewModel = ({
// Prometheus Results Parsing
const dateTimeFromUnixTime = unixTime => new Date(unixTime * 1000).toISOString();
const dateTimeFromUnixTime = (unixTime) => new Date(unixTime * 1000).toISOString();
const mapScalarValue = ([unixTime, value]) => [dateTimeFromUnixTime(unixTime), Number(value)];
......@@ -324,7 +324,7 @@ const mapStringValue = ([unixTime, value]) => [dateTimeFromUnixTime(unixTime), v
* @param {array} result
* @returns {array}
*/
const normalizeScalarResult = result => [
const normalizeScalarResult = (result) => [
{
metric: {},
value: mapScalarValue(result),
......@@ -344,7 +344,7 @@ const normalizeScalarResult = result => [
* @param {array} result
* @returns {array}
*/
const normalizeStringResult = result => [
const normalizeStringResult = (result) => [
{
metric: {},
value: mapStringValue(result),
......@@ -379,7 +379,7 @@ const normalizeStringResult = result => [
* @param {array} result
* @returns {array}
*/
const normalizeVectorResult = result =>
const normalizeVectorResult = (result) =>
result.map(({ metric, value }) => {
const scalar = mapScalarValue(value);
// Add a single element to `values`, to support matrix
......@@ -407,7 +407,7 @@ const normalizeVectorResult = result =>
* @param {array} result
* @returns {object} Normalized result.
*/
const normalizeResultMatrix = result =>
const normalizeResultMatrix = (result) =>
result.map(({ metric, values }) => {
const mappedValues = values.map(mapScalarValue);
return {
......@@ -440,7 +440,7 @@ const normalizeResultMatrix = result =>
* ]
*
*/
export const normalizeQueryResponseData = data => {
export const normalizeQueryResponseData = (data) => {
const { resultType, result } = data;
if (resultType === 'vector') {
return normalizeVectorResult(result);
......@@ -466,7 +466,7 @@ export const normalizeQueryResponseData = data => {
* @param {String} name Variable key that needs to be prefixed
* @returns {String}
*/
export const addPrefixToCustomVariableParams = name => `variables[${name}]`;
export const addPrefixToCustomVariableParams = (name) => `variables[${name}]`;
/**
* Normalize custom dashboard paths. This method helps support
......
......@@ -21,7 +21,7 @@ import { VARIABLE_TYPES } from '../constants';
* @param {String|Object} simpleTextVar
* @returns {Object}
*/
const textSimpleVariableParser = simpleTextVar => ({
const textSimpleVariableParser = (simpleTextVar) => ({
type: VARIABLE_TYPES.text,
label: null,
value: simpleTextVar,
......@@ -34,7 +34,7 @@ const textSimpleVariableParser = simpleTextVar => ({
* @param {Object} advTextVar
* @returns {Object}
*/
const textAdvancedVariableParser = advTextVar => ({
const textAdvancedVariableParser = (advTextVar) => ({
type: VARIABLE_TYPES.text,
label: advTextVar.label,
value: advTextVar.options.default_value,
......@@ -62,9 +62,9 @@ const normalizeVariableValues = ({ default: defaultOpt = false, text, value = nu
* @param {Object} advVariable advanced custom variable
* @returns {Object}
*/
const customAdvancedVariableParser = advVariable => {
const customAdvancedVariableParser = (advVariable) => {
const values = (advVariable?.options?.values ?? []).map(normalizeVariableValues);
const defaultValue = values.find(opt => opt.default === true) || values[0];
const defaultValue = values.find((opt) => opt.default === true) || values[0];
return {
type: VARIABLE_TYPES.custom,
label: advVariable.label,
......@@ -82,7 +82,7 @@ const customAdvancedVariableParser = advVariable => {
* @param {String} opt option from simple custom variable
* @returns {Object}
*/
export const parseSimpleCustomValues = opt => ({ text: opt, value: opt });
export const parseSimpleCustomValues = (opt) => ({ text: opt, value: opt });
/**
* Custom simple variables are rendered as dropdown elements in the dashboard
......@@ -96,7 +96,7 @@ export const parseSimpleCustomValues = opt => ({ text: opt, value: opt });
* @param {Array} customVariable array of options
* @returns {Object}
*/
const customSimpleVariableParser = simpleVar => {
const customSimpleVariableParser = (simpleVar) => {
const values = (simpleVar || []).map(parseSimpleCustomValues);
return {
type: VARIABLE_TYPES.custom,
......@@ -126,7 +126,7 @@ const metricLabelValuesVariableParser = ({ label, options = {} }) => ({
* @param {Array|Object} customVar Array if simple, object if advanced
* @returns {Boolean} true if simple, false if advanced
*/
const isSimpleCustomVariable = customVar => Array.isArray(customVar);
const isSimpleCustomVariable = (customVar) => Array.isArray(customVar);
/**
* This method returns a parser based on the type of the variable.
......@@ -137,7 +137,7 @@ const isSimpleCustomVariable = customVar => Array.isArray(customVar);
* @param {Array|Object} variable
* @return {Function} parser method
*/
const getVariableParser = variable => {
const getVariableParser = (variable) => {
if (isString(variable)) {
return textSimpleVariableParser;
} else if (isSimpleCustomVariable(variable)) {
......@@ -200,7 +200,7 @@ export const parseTemplatingVariables = (ymlVariables = {}) =>
*/
export const mergeURLVariables = (parsedYmlVariables = []) => {
const varsFromURL = templatingVariablesFromUrl();
parsedYmlVariables.forEach(variable => {
parsedYmlVariables.forEach((variable) => {
const { name } = variable;
if (Object.prototype.hasOwnProperty.call(varsFromURL, name)) {
Object.assign(variable, { value: varsFromURL[name] });
......
......@@ -81,15 +81,15 @@ export const graphDataValidatorForValues = (isValues, graphData) => {
const responseValueKeyName = isValues ? 'value' : 'values';
return (
Array.isArray(graphData.metrics) &&
graphData.metrics.filter(query => {
graphData.metrics.filter((query) => {
if (Array.isArray(query.result)) {
return (
query.result.filter(res => Array.isArray(res[responseValueKeyName])).length ===
query.result.filter((res) => Array.isArray(res[responseValueKeyName])).length ===
query.result.length
);
}
return false;
}).length === graphData.metrics.filter(query => query.result).length
}).length === graphData.metrics.filter((query) => query.result).length
);
};
......@@ -106,7 +106,7 @@ const isClusterHealthBoard = () => (document.body.dataset.page || '').includes('
* @param {String} chart link that will be sent as a property for the event
* @return {Object} config object for event tracking
*/
export const generateLinkToChartOptions = chartLink => {
export const generateLinkToChartOptions = (chartLink) => {
const isCLusterHealthBoard = isClusterHealthBoard();
const category = isCLusterHealthBoard
......@@ -124,7 +124,7 @@ export const generateLinkToChartOptions = chartLink => {
* @param {String} chart title that will be sent as a property for the event
* @return {Object} config object for event tracking
*/
export const downloadCSVOptions = title => {
export const downloadCSVOptions = (title) => {
const isCLusterHealthBoard = isClusterHealthBoard();
const category = isCLusterHealthBoard
......@@ -157,7 +157,7 @@ export const getAddMetricTrackingOptions = () => ({
* @param {Object} graphData the graph data response from a prometheus request
* @returns {boolean} true if the data is valid
*/
export const graphDataValidatorForAnomalyValues = graphData => {
export const graphDataValidatorForAnomalyValues = (graphData) => {
const anomalySeriesCount = 3; // metric, upper, lower
return (
graphData.metrics &&
......@@ -186,7 +186,7 @@ export const timeRangeFromUrl = (search = window.location.search) => {
* @param {String} label label for the template variable
* @returns {String}
*/
export const addPrefixToLabel = label => `${VARIABLE_PREFIX}${label}`;
export const addPrefixToLabel = (label) => `${VARIABLE_PREFIX}${label}`;
/**
* Before the templating variables are passed to the backend the
......@@ -197,7 +197,7 @@ export const addPrefixToLabel = label => `${VARIABLE_PREFIX}${label}`;
* @param {String} label label to remove prefix from
* @returns {String}
*/
export const removePrefixFromLabel = label =>
export const removePrefixFromLabel = (label) =>
(label || '').replace(new RegExp(`^${VARIABLE_PREFIX}`), '');
/**
......@@ -210,7 +210,7 @@ export const removePrefixFromLabel = label =>
* @param {Object} variables
* @returns {Object}
*/
export const convertVariablesForURL = variables =>
export const convertVariablesForURL = (variables) =>
variables.reduce((acc, { name, value }) => {
if (value !== null) {
acc[addPrefixToLabel(name)] = value;
......@@ -241,7 +241,7 @@ export const templatingVariablesFromUrl = (search = window.location.search) => {
*
* @param {Object} variables user defined variables
*/
export const setCustomVariablesFromUrl = variables => {
export const setCustomVariablesFromUrl = (variables) => {
// prep the variables to append to URL
const parsedVariables = convertVariablesForURL(variables);
// update the URL
......@@ -353,7 +353,7 @@ export const panelToUrl = (
* @param {Array} values data points
* @returns {Number}
*/
const metricValueMapper = values => values[0]?.[1];
const metricValueMapper = (values) => values[0]?.[1];
/**
* Get the metric name from metric object
......@@ -364,7 +364,7 @@ const metricValueMapper = values => values[0]?.[1];
* @param {Object} metric metric object
* @returns {String}
*/
const metricNameMapper = metric => Object.values(metric)?.[0];
const metricNameMapper = (metric) => Object.values(metric)?.[0];
/**
* Parse metric object to extract metric value and name in
......
import { isSafeURL } from '~/lib/utils/url_utility';
const isRunbookUrlValid = runbookUrl => {
const isRunbookUrlValid = (runbookUrl) => {
if (!runbookUrl) {
return true;
}
......@@ -21,7 +21,7 @@ const isRunbookUrlValid = runbookUrl => {
// }
// }
export function alertsValidator(value) {
return Object.keys(value).every(key => {
return Object.keys(value).every((key) => {
const alert = value[key];
return (
alert.alert_path &&
......@@ -49,7 +49,7 @@ export function alertsValidator(value) {
// ]
export function queriesValidator(value) {
return value.every(
query =>
(query) =>
query.metricId && typeof query.metricId === 'string' && typeof query.label === 'string',
);
}
......@@ -33,7 +33,7 @@ export default () => {
computed: {
...mapGetters(['discussionTabCounter']),
...mapState({
activeTab: state => state.page.activeTab,
activeTab: (state) => state.page.activeTab,
}),
isShowTabActive() {
return this.activeTab === 'show';
......
// Note: this getter is important because
// `noteableData` is namespaced under `notes` for `~/mr_notes/stores`
// while `noteableData` is directly available as `state.noteableData` for `~/notes/stores`
export const getNoteableData = state => state.notes.noteableData;
export const getNoteableData = (state) => state.notes.noteableData;
export default {
isLoggedIn(state, getters) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment