chore(prettier): use arrow-parens: avoid

pull/5690/head
Pavel Zavora 2021-03-08 12:45:09 +01:00
parent 05dad39a04
commit e1b9589a28
84 changed files with 370 additions and 403 deletions

View File

@ -413,7 +413,7 @@ export const updateTimeRangeQueryParams = (
...parsed,
...updatedQueryParams,
},
(v) => !!v
v => !!v
)
const newSearch = qs.stringify(newQueryParams)
@ -431,7 +431,7 @@ export const updateQueryParams = (updatedQueryParams: object): RouterAction => {
...qs.parse(search, {ignoreQueryPrefix: true}),
...updatedQueryParams,
},
(v) => !!v
v => !!v
)
const newSearch = qs.stringify(newQueryParams)
@ -441,9 +441,7 @@ export const updateQueryParams = (updatedQueryParams: object): RouterAction => {
}
const getDashboard = (state, dashboardId: string): Dashboard => {
const dashboard = state.dashboardUI.dashboards.find(
(d) => d.id === dashboardId
)
const dashboard = state.dashboardUI.dashboards.find(d => d.id === dashboardId)
if (!dashboard) {
throw new Error(`Could not find dashboard with id '${dashboardId}'`)
@ -481,7 +479,7 @@ export const getChronografVersion = () => async (): Promise<string> => {
const removeUnselectedTemplateValues = (dashboard: Dashboard): Template[] => {
const templates = getDeep<Template[]>(dashboard, 'templates', []).map(
(template) => {
template => {
if (
template.type === TemplateType.CSV ||
template.type === TemplateType.Map
@ -489,7 +487,7 @@ const removeUnselectedTemplateValues = (dashboard: Dashboard): Template[] => {
return template
}
const value = template.values.find((val) => val.selected)
const value = template.values.find(val => val.selected)
const values = value ? [value] : []
return {...template, values}
@ -696,7 +694,7 @@ const updateTimeRangeFromQueryParams = (dashboardID: string) => (
if (!validatedTimeRange.lower) {
const dashboardTimeRange = dashTimeV1.ranges.find(
(r) => r.dashboardID === dashboardID
r => r.dashboardID === dashboardID
)
validatedTimeRange = dashboardTimeRange || DEFAULT_TIME_RANGE
@ -758,9 +756,9 @@ export const getDashboardWithTemplatesAsync = (
_.each(selections, (val, key) => {
const result = _.some(
templates,
(temp) =>
temp =>
temp.tempVar === key &&
_.some(temp.values, (v) => {
_.some(temp.values, v => {
if (v.key) {
return v.key === val
}

View File

@ -38,7 +38,7 @@ export const loadDashboardLinks = async (
return dashboardLinks
}
export const getDashboard = async (dashboardID) => {
export const getDashboard = async dashboardID => {
try {
const url = `/chronograf/v1/dashboards/${dashboardID}`
return manager.get(url)
@ -48,7 +48,7 @@ export const getDashboard = async (dashboardID) => {
}
}
export const updateDashboard = (dashboard) => {
export const updateDashboard = dashboard => {
return AJAX({
method: 'PUT',
url: dashboard.links.self,
@ -56,7 +56,7 @@ export const updateDashboard = (dashboard) => {
})
}
export const updateDashboardCell = (cell) => {
export const updateDashboardCell = cell => {
return AJAX({
method: 'PUT',
url: cell.links.self,
@ -64,7 +64,7 @@ export const updateDashboardCell = (cell) => {
})
}
export const createDashboard = async (dashboard) => {
export const createDashboard = async dashboard => {
try {
return await AJAX({
method: 'POST',
@ -94,7 +94,7 @@ export const createDashboardFromProtoboard = async (
}
}
export const deleteDashboard = async (dashboard) => {
export const deleteDashboard = async dashboard => {
try {
return await AJAX({
method: 'DELETE',
@ -119,7 +119,7 @@ export const addDashboardCell = async (dashboard, cell) => {
}
}
export const deleteDashboardCell = async (cell) => {
export const deleteDashboardCell = async cell => {
try {
return await AJAX({
method: 'DELETE',
@ -131,7 +131,7 @@ export const deleteDashboardCell = async (cell) => {
}
}
export const editTemplateVariables = async (templateVariable) => {
export const editTemplateVariables = async templateVariable => {
try {
return await AJAX({
method: 'PUT',

View File

@ -22,7 +22,7 @@ export default (state: State = initialState, action: Action) => {
switch (action.type) {
case ActionType.DeleteDashboard: {
const {dashboard} = action.payload
const ranges = state.ranges.filter((r) => r.dashboardID !== dashboard.id)
const ranges = state.ranges.filter(r => r.dashboardID !== dashboard.id)
return {...state, ranges}
}
@ -36,7 +36,7 @@ export default (state: State = initialState, action: Action) => {
return accum
}, dashboardIDsHash)
}
const ranges = state.ranges.filter((r) => dashboardIDsHash[r.dashboardID])
const ranges = state.ranges.filter(r => dashboardIDsHash[r.dashboardID])
return {...state, ranges}
}
@ -50,7 +50,7 @@ export default (state: State = initialState, action: Action) => {
}, dashboardIDsHash)
}
const refreshes = state.refreshes.filter(
(r) => dashboardIDsHash[r.dashboardID]
r => dashboardIDsHash[r.dashboardID]
)
return {...state, refreshes}
}

View File

@ -6,7 +6,7 @@ import {Action, ActionType} from 'src/dashboards/actions'
import {TemplateType} from 'src/types/tempVars'
const {lower, upper} = timeRanges.find((tr) => tr.lower === 'now() - 1h')
const {lower, upper} = timeRanges.find(tr => tr.lower === 'now() - 1h')
export const initialState: DashboardUIState = {
dashboards: [],
@ -54,7 +54,7 @@ export default (
case ActionType.UpdateDashboard: {
const {dashboard} = action.payload
const newState = {
dashboards: state.dashboards.map((d) =>
dashboards: state.dashboards.map(d =>
d.id === dashboard.id ? dashboard : d
),
}
@ -72,7 +72,7 @@ export default (
case ActionType.DeleteDashboard: {
const {dashboard} = action.payload
const newState = {
dashboards: state.dashboards.filter((d) => d.id !== dashboard.id),
dashboards: state.dashboards.filter(d => d.id !== dashboard.id),
}
return {...state, ...newState}
@ -92,7 +92,7 @@ export default (
const newCells = [cell, ...dashboard.cells]
const newDashboard = {...dashboard, cells: newCells}
const newDashboards = dashboards.map((d) =>
const newDashboards = dashboards.map(d =>
d.id === dashboard.id ? newDashboard : d
)
const newState = {dashboards: newDashboards}
@ -104,14 +104,14 @@ export default (
const {dashboard, cell} = action.payload
const newCells = dashboard.cells.filter(
(c) => !(c.x === cell.x && c.y === cell.y)
c => !(c.x === cell.x && c.y === cell.y)
)
const newDashboard = {
...dashboard,
cells: newCells,
}
const newState = {
dashboards: state.dashboards.map((d) =>
dashboards: state.dashboards.map(d =>
d.id === dashboard.id ? newDashboard : d
),
}
@ -124,13 +124,13 @@ export default (
const newDashboard = {
...dashboard,
cells: dashboard.cells.map((c) =>
cells: dashboard.cells.map(c =>
c.x === cell.x && c.y === cell.y ? cell : c
),
}
const newState = {
dashboards: state.dashboards.map((d) =>
dashboards: state.dashboards.map(d =>
d.id === dashboard.id ? newDashboard : d
),
}
@ -147,12 +147,12 @@ export default (
case ActionType.TemplateVariableLocalSelected: {
const {dashboardID, templateID, value: newValue} = action.payload
const dashboards = state.dashboards.map((dashboard) => {
const dashboards = state.dashboards.map(dashboard => {
if (dashboard.id !== dashboardID) {
return dashboard
}
const templates = dashboard.templates.map((template) => {
const templates = dashboard.templates.map(template => {
if (template.id !== templateID) {
return template
}
@ -161,7 +161,7 @@ export default (
if (template.type === TemplateType.Text) {
values = [newValue]
} else {
values = template.values.map((value) => {
values = template.values.map(value => {
const localSelected = value.value === newValue.value
return {...value, localSelected}
@ -180,11 +180,11 @@ export default (
case ActionType.UpdateTemplates: {
const {templates: updatedTemplates} = action.payload
const dashboards = state.dashboards.map((dashboard) => {
const dashboards = state.dashboards.map(dashboard => {
const templates = dashboard.templates.reduce(
(acc, existingTemplate) => {
const updatedTemplate = updatedTemplates.find(
(t) => t.id === existingTemplate.id
t => t.id === existingTemplate.id
)
if (updatedTemplate) {

View File

@ -43,15 +43,13 @@ export const isCellUntitled = (cellName: string): boolean => {
}
export const getNextAvailablePosition = (cells, newCell) => {
const farthestY = cells
.map((cell) => cell.y)
.reduce((a, b) => (a > b ? a : b))
const farthestY = cells.map(cell => cell.y).reduce((a, b) => (a > b ? a : b))
const bottomCells = cells.filter((cell) => cell.y === farthestY)
const bottomCells = cells.filter(cell => cell.y === farthestY)
const farthestX = bottomCells
.map((cell) => cell.x)
.map(cell => cell.x)
.reduce((a, b) => (a > b ? a : b))
const lastCell = bottomCells.find((cell) => cell.x === farthestX)
const lastCell = bottomCells.find(cell => cell.x === farthestX)
const availableSpace = MAX_COLUMNS - (lastCell.x + lastCell.w)
const newCellFits = availableSpace >= newCell.w
@ -81,8 +79,8 @@ export const getNewDashboardCell = (
return typedCell
}
const existingCellWidths = dashboard.cells.map((cell) => cell.w)
const existingCellHeights = dashboard.cells.map((cell) => cell.h)
const existingCellWidths = dashboard.cells.map(cell => cell.w)
const existingCellHeights = dashboard.cells.map(cell => cell.h)
const mostCommonCellWidth = getMostCommonValue(existingCellWidths)
const mostCommonCellHeight = getMostCommonValue(existingCellHeights)
@ -105,7 +103,7 @@ export const getNewDashboardCell = (
const incrementCloneName = (cellNames: string[], cellName: string): string => {
const rootName = cellName.replace(/\s\(clone\s(\d)+\)/g, '').replace(/\)/, '')
const filteredNames = cellNames.filter((cn) => cn.includes(rootName))
const filteredNames = cellNames.filter(cn => cn.includes(rootName))
const highestNumberedClone = filteredNames.reduce((acc, name) => {
if (name.match(/\(clone(\s|\d)+\)/)) {
@ -137,7 +135,7 @@ export const getClonedDashboardCell = (
dashboard: Dashboard,
cellClone: Cell
): Cell => {
const cellNames = dashboard.cells.map((c) => c.name)
const cellNames = dashboard.cells.map(c => c.name)
const name = incrementCloneName(cellNames, cellClone.name)
const cellCloneFitsLeft = cellClone.x >= cellClone.w
@ -183,7 +181,7 @@ export const getConfig = async (
const queries = await getQueryConfigAndStatus(url, [
{query: renderedQuery, id},
])
const {queryConfig} = queries.find((q) => q.id === id)
const {queryConfig} = queries.find(q => q.id === id)
const range = getRangeForOriginalQuery(query, queryConfig.range)
return {

View File

@ -10,7 +10,7 @@ export const linksFromDashboards = (
dashboards: Dashboard[],
source: Source
): DashboardSwitcherLinks => {
const links = dashboards.map((d) => {
const links = dashboards.map(d => {
return {
key: String(d.id),
text: d.name,
@ -43,7 +43,7 @@ const updateActiveDashboardLink = (
dashboard: Dashboard
) => {
const active = dashboardLinks.links.find(
(link) => link.key === String(dashboard.id)
link => link.key === String(dashboard.id)
)
return {...dashboardLinks, active}
@ -56,7 +56,7 @@ const updateActiveDashboardLinkName = (
const {name} = dashboard
let {active} = dashboardLinks
const links = dashboardLinks.links.map((link) => {
const links = dashboardLinks.links.map(link => {
if (link.key === String(dashboard.id)) {
active = {...link, text: name}

View File

@ -17,7 +17,7 @@ export const mapSourcesForDownload = (originalSources: Source[]) =>
)
export const mapQueriesToSources = (queries: CellQuery[]) => {
return queries.map((query) => {
return queries.map(query => {
return {
...query,
source: query.source,
@ -26,7 +26,7 @@ export const mapQueriesToSources = (queries: CellQuery[]) => {
}
export const mapCellsToSources = (cells: Cell[]) => {
return cells.map((cell) => {
return cells.map(cell => {
const {queries} = cell
return {

View File

@ -47,7 +47,7 @@ export const createSourceMappings = (
let importedSourceID = _.findKey(
importedSources,
(is) => is.link === sourceLink
is => is.link === sourceLink
)
if (!importedSourceID) {
const sourceLinkSID = getSourceIDFromLink(sourceLink)
@ -68,7 +68,7 @@ export const createSourceMappings = (
sourcesCells
)
// add sources also for variables
variables.forEach((v) => {
variables.forEach(v => {
if (v.sourceID && !sourceMappings[v.sourceID]) {
sourceMappings[v.sourceID] = sourceInfo
sourcesCells[v.sourceID] = []
@ -88,7 +88,7 @@ export const mapCells = (
sourceMappings: SourceMappings,
importedSources: ImportedSources
): Cell[] => {
const mappedCells = cells.map((c) => {
const mappedCells = cells.map(c => {
const query = getDeep<CellQuery>(c, 'queries.0', null)
if (_.isEmpty(query)) {
return c
@ -101,7 +101,7 @@ export const mapCells = (
let importedSourceID = _.findKey(
importedSources,
(is) => is.link === sourceLink
is => is.link === sourceLink
)
if (!importedSourceID) {
const sourceLinkSID = getSourceIDFromLink(sourceLink)
@ -128,7 +128,7 @@ export const mapQueriesInCell = (
const mappedSourceLink = sourceMappings[sourceID].link
let queries = getDeep<CellQuery[]>(cell, 'queries', [])
if (queries.length) {
queries = queries.map((q) => {
queries = queries.map(q => {
return {...q, source: mappedSourceLink}
})
}

View File

@ -64,8 +64,8 @@ export const addAppsToHosts = async (
const measurementsList: string[] = []
const measurementsToProtoboards = {}
_.forEach(protoboards, (pb) => {
_.forEach(pb.meta.measurements, (m) => {
_.forEach(protoboards, pb => {
_.forEach(pb.meta.measurements, m => {
measurementsToProtoboards[m] = pb.meta.name
measurementsList.push(m)
})
@ -77,7 +77,7 @@ export const addAppsToHosts = async (
const allSeries = await getAllSeries(source, joinedMeasurements)
allSeries.forEach((series) => {
allSeries.forEach(series => {
const {measurement, host} = parseSeries(series)
if (!newHosts[host]) {
return
@ -110,9 +110,9 @@ export const getHosts = async (source: Source): Promise<Hosts> => {
['data', 'results', '0', 'series'],
[]
)
allHostsSeries.forEach((s) => {
const hostnameIndex = s.columns.findIndex((col) => col === 'value')
s.values.forEach((v) => {
allHostsSeries.forEach(s => {
const hostnameIndex = s.columns.findIndex(col => col === 'value')
s.values.forEach(v => {
const hostname = v[hostnameIndex]
hosts[hostname] = {}
})

View File

@ -37,7 +37,7 @@ const addNewCellToCells = (
const createTemplatesForProtoboard = (pbTemplates, source): Template[] => {
const telegraf = source.telegraf || 'telegraf'
return pbTemplates.map((pbt) => {
return pbTemplates.map(pbt => {
return {...pbt, id: uuid.v4(), query: {...pbt.query, db: telegraf}}
})
}
@ -48,7 +48,7 @@ const replaceQuery = (q: string, source: Source) =>
.replace(':rp:', source.defaultRP || 'autogen')
const replaceDbRp = (queries: CellQuery[], source: Source) =>
queries.map((q) => ({...q, query: replaceQuery(q.query, source)}))
queries.map(q => ({...q, query: replaceQuery(q.query, source)}))
export const instantiateProtoboard = (
protoboard: Protoboard,
@ -57,7 +57,7 @@ export const instantiateProtoboard = (
let cellsWithPlaces = protoboard.data.cells
const isCellsUnplaced = protoboard.data.cells.every(
(c) => c.x === 0 && c.y === 0
c => c.x === 0 && c.y === 0
)
if (isCellsUnplaced) {
@ -67,7 +67,7 @@ export const instantiateProtoboard = (
const pbTemplates = protoboard.data.templates
const templates = createTemplatesForProtoboard(pbTemplates, source)
const cells = cellsWithPlaces.map((c) => ({
const cells = cellsWithPlaces.map(c => ({
...c,
queries: replaceDbRp(c.queries, source),
})) as Cell[]

View File

@ -84,7 +84,7 @@ const updateMaxWidths = (
const foundField =
isLabel && _.isString(col)
? fieldOptions.find((field) => field.internalName === col)
? fieldOptions.find(field => field.internalName === col)
: null
let colValue = `${col}`
@ -167,12 +167,12 @@ export const computeFieldOptions = (
return astNames
}
const intersection = existingFieldOptions.filter((f) => {
return astNames.find((a) => a.internalName === f.internalName)
const intersection = existingFieldOptions.filter(f => {
return astNames.find(a => a.internalName === f.internalName)
})
const newFields = astNames.filter((a) => {
return !existingFieldOptions.find((f) => f.internalName === a.internalName)
const newFields = astNames.filter(a => {
return !existingFieldOptions.find(f => f.internalName === a.internalName)
})
return [...intersection, ...newFields]
@ -218,7 +218,7 @@ export const filterTableColumns = (
return fastFilter<TimeSeriesValue>(row, (col, j) => {
if (i === 0) {
const foundField = fieldOptions.find(
(field) => field.internalName === col
field => field.internalName === col
)
visibility[j] = foundField ? foundField.visible : true
}
@ -233,13 +233,13 @@ export const orderTableColumns = (
data: TimeSeriesValue[][],
fieldOptions: FieldOption[]
): TimeSeriesValue[][] => {
const fieldsSortOrder = fieldOptions.map((fieldOption) => {
return _.findIndex(data[0], (dataLabel) => {
const fieldsSortOrder = fieldOptions.map(fieldOption => {
return _.findIndex(data[0], dataLabel => {
return dataLabel === fieldOption.internalName
})
})
const filteredFieldSortOrder = fieldsSortOrder.filter((f) => f !== -1)
const filteredFieldSortOrder = fieldsSortOrder.filter(f => f !== -1)
const orderedData = fastMap<TimeSeriesValue[], TimeSeriesValue[]>(
data,

View File

@ -23,7 +23,7 @@ export const templateSelectionsFromTemplates = (
): TemplateSelections => {
return templates.reduce((acc, template) => {
const tempVar = stripTempVar(template.tempVar)
const selection = template.values.find((t) => t.localSelected)
const selection = template.values.find(t => t.localSelected)
if (!selection) {
return acc
@ -39,7 +39,7 @@ export const stripTempVar = (tempVarName: string): string =>
tempVarName.substr(1, tempVarName.length - 2)
const makeSelected = (template: Template, value: string): Template => {
const found = template.values.find((v) => v.value === value)
const found = template.values.find(v => v.value === value)
let valueToChoose
if (found) {
@ -48,7 +48,7 @@ const makeSelected = (template: Template, value: string): Template => {
valueToChoose = getDeep<string>(template, 'values.0.value', '')
}
const valuesWithSelected = template.values.map((v) => {
const valuesWithSelected = template.values.map(v => {
if (v.value === valueToChoose) {
return {...v, selected: true}
} else {
@ -69,8 +69,8 @@ export const makeLocalSelected = (
template: Template,
value: string
): Template => {
const found = template.values.find((v) => v.value === value)
const selectedValue = template.values.find((v) => v.selected)
const found = template.values.find(v => v.value === value)
const selectedValue = template.values.find(v => v.selected)
let valueToChoose: string
if (found) {
@ -81,7 +81,7 @@ export const makeLocalSelected = (
valueToChoose = getDeep<string>(template, 'values.0.value', '')
}
const valuesWithLocalSelected = template.values.map((v) => {
const valuesWithLocalSelected = template.values.map(v => {
if (v.value === valueToChoose) {
return {...v, localSelected: true}
} else {
@ -96,8 +96,8 @@ export const reconcileSelectedAndLocalSelectedValues = (
nextTemplate: Template,
nextNextTemplate: Template
): Template => {
const localSelectedValue = nextTemplate.values.find((v) => v.localSelected)
const selectedValue = nextTemplate.values.find((v) => v.selected)
const localSelectedValue = nextTemplate.values.find(v => v.localSelected)
const selectedValue = nextTemplate.values.find(v => v.selected)
const templateWithLocalSelected = makeSelected(
nextNextTemplate,
getDeep<string>(selectedValue, 'value', '')

View File

@ -37,7 +37,7 @@ export const millisecondTimeRange = ({
const nullTimeRange: TimeRange = {lower: null, upper: null}
const validRelativeTimeRange = (timeRange: TimeRange): TimeRange => {
const validatedTimeRange = timeRanges.find((t) => t.lower === timeRange.lower)
const validatedTimeRange = timeRanges.find(t => t.lower === timeRange.lower)
if (validatedTimeRange) {
return validatedTimeRange

View File

@ -399,7 +399,7 @@ export const editRawTextAsync = (
query: text,
},
])
const config = queries.find((q) => q.id === id)
const config = queries.find(q => q.id === id)
dispatch(updateQueryConfig(config.queryConfig))
} catch (error) {
dispatch(errorThrown(error))

View File

@ -249,5 +249,5 @@ export const WRITE_DATA_DOCS_LINK =
'https://docs.influxdata.com/influxdb/latest/write_protocols/line_protocol_tutorial/'
export const DEFAULT_TIME_RANGE = timeRanges.find(
(tr) => tr.lower === 'now() - 1h'
tr => tr.lower === 'now() - 1h'
)

View File

@ -1,7 +1,7 @@
import {timeRanges} from 'src/shared/data/timeRanges'
import {TimeRange} from 'src/types'
const {lower, upper} = timeRanges.find((tr) => tr.lower === 'now() - 1h')
const {lower, upper} = timeRanges.find(tr => tr.lower === 'now() - 1h')
const initialState = {
upper,

View File

@ -258,9 +258,9 @@ export const getFunctionSuggestions = (
const currentWord = currentLineText.slice(start, end)
const listFilter = new RegExp(`^${currentWord}`, 'i')
const suggestions = allSuggestions
.map((s) => s.name)
.filter((name) => name.match(listFilter))
.map((displayText) => ({text: formatter(displayText), displayText}))
.map(s => s.name)
.filter(name => name.match(listFilter))
.map(displayText => ({text: formatter(displayText), displayText}))
return {start, end, suggestions}
}

View File

@ -76,9 +76,9 @@ export const getCpuAndLoadForHosts = async (
const winUptimeSeries = getDeep<Series[]>(data, 'results.[5].series', [])
const allHostsSeries = getDeep<Series[]>(data, 'results.[6].series', [])
allHostsSeries.forEach((s) => {
const hostnameIndex = s.columns.findIndex((col) => col === 'value')
s.values.forEach((v) => {
allHostsSeries.forEach(s => {
const hostnameIndex = s.columns.findIndex(col => col === 'value')
s.values.forEach(v => {
const hostname = v[hostnameIndex]
hosts[hostname] = {
...EmptyHost,
@ -87,8 +87,8 @@ export const getCpuAndLoadForHosts = async (
})
})
cpuSeries.forEach((s) => {
const meanIndex = s.columns.findIndex((col) => col === 'mean')
cpuSeries.forEach(s => {
const meanIndex = s.columns.findIndex(col => col === 'mean')
hosts[s.tags.host] = {
...EmptyHost,
name: s.tags.host,
@ -96,37 +96,35 @@ export const getCpuAndLoadForHosts = async (
}
})
loadSeries.forEach((s) => {
const meanIndex = s.columns.findIndex((col) => col === 'mean')
loadSeries.forEach(s => {
const meanIndex = s.columns.findIndex(col => col === 'mean')
hosts[s.tags.host].load =
Math.round(Number(s.values[0][meanIndex]) * precision) / precision
})
uptimeSeries.forEach((s) => {
const uptimeIndex = s.columns.findIndex((col) => col === 'deltaUptime')
uptimeSeries.forEach(s => {
const uptimeIndex = s.columns.findIndex(col => col === 'deltaUptime')
hosts[s.tags.host].deltaUptime = Number(
s.values[s.values.length - 1][uptimeIndex]
)
})
winCPUSeries.forEach((s) => {
const meanIndex = s.columns.findIndex((col) => col === 'mean')
winCPUSeries.forEach(s => {
const meanIndex = s.columns.findIndex(col => col === 'mean')
hosts[s.tags.host] = {
name: s.tags.host,
cpu: Math.round(Number(s.values[0][meanIndex]) * precision) / precision,
}
})
winLoadSeries.forEach((s) => {
const meanIndex = s.columns.findIndex((col) => col === 'mean')
winLoadSeries.forEach(s => {
const meanIndex = s.columns.findIndex(col => col === 'mean')
hosts[s.tags.host].load =
Math.round(Number(s.values[0][meanIndex]) * precision) / precision
})
winUptimeSeries.forEach((s) => {
const winUptimeIndex = s.columns.findIndex(
(col) => col === 'winDeltaUptime'
)
winUptimeSeries.forEach(s => {
const winUptimeIndex = s.columns.findIndex(col => col === 'winDeltaUptime')
hosts[s.tags.host].winDeltaUptime = Number(
s.values[s.values.length - 1][winUptimeIndex]
)
@ -151,9 +149,9 @@ const getAllHosts = async (source: Source): Promise<HostNames> => {
const hosts: HostNames = {}
const allHostsSeries = getDeep<Series[]>(data, 'results[0].series', [])
allHostsSeries.forEach((s) => {
const hostnameIndex = s.columns.findIndex((col) => col === 'value')
s.values.forEach((v) => {
allHostsSeries.forEach(s => {
const hostnameIndex = s.columns.findIndex(col => col === 'value')
s.values.forEach(v => {
const hostname = v[hostnameIndex]
hosts[hostname] = {
name: hostname,
@ -202,9 +200,9 @@ export const getAppsForHost = async (
appLayouts: Layout[],
telegrafDB: string
) => {
const measurements = appLayouts.map((m) => `^${m.measurement}$`).join('|')
const measurements = appLayouts.map(m => `^${m.measurement}$`).join('|')
const measurementsToApps = _.zipObject(
appLayouts.map((m) => m.measurement),
appLayouts.map(m => m.measurement),
appLayouts.map(({app}) => app)
)
@ -218,7 +216,7 @@ export const getAppsForHost = async (
const allSeries = getDeep<string[][]>(data, 'results.0.series.0.values', [])
allSeries.forEach((series) => {
allSeries.forEach(series => {
const seriesObj = parseSeries(series[0])
const measurement = seriesObj.measurement
@ -236,9 +234,9 @@ export const getAppsForHosts = async (
appLayouts: Layout[],
telegrafDB: string
): Promise<HostsObject> => {
const measurements = appLayouts.map((m) => `^${m.measurement}$`).join('|')
const measurements = appLayouts.map(m => `^${m.measurement}$`).join('|')
const measurementsToApps = _.zipObject(
appLayouts.map((m) => m.measurement),
appLayouts.map(m => m.measurement),
appLayouts.map(({app}) => app)
)
@ -255,7 +253,7 @@ export const getAppsForHosts = async (
[]
)
allSeries.forEach((series) => {
allSeries.forEach(series => {
const seriesObj = parseSeries(series[0])
const measurement = seriesObj.measurement
const host = getDeep<string>(seriesObj, 'tags.host', '')
@ -295,7 +293,7 @@ export const getMeasurementsForHost = async (
}
const values = getDeep<string[][]>(data, 'results.[0].series.[0].values', [])
const measurements = values.map((m) => {
const measurements = values.map(m => {
return m[0]
})
return measurements

View File

@ -12,7 +12,7 @@ const PAGE_WIDTH = 12
export function getCells(layouts: Layout[], source: Source): Cell[] {
const layoutCells = getLayoutCells(layouts)
const cells = layoutCells.map((d) => toCell(d, source))
const cells = layoutCells.map(d => toCell(d, source))
return cells
}
@ -22,13 +22,13 @@ function getLayoutCells(layouts: Layout[]): LayoutCell[] {
return []
}
const autoflowLayouts = layouts.filter((l) => !!l.autoflow)
const autoflowCells = flatten(autoflowLayouts.map((l) => l.cells))
const autoflowLayouts = layouts.filter(l => !!l.autoflow)
const autoflowCells = flatten(autoflowLayouts.map(l => l.cells))
const staticLayouts = layouts.filter((layout) => !layout.autoflow)
const staticLayouts = layouts.filter(layout => !layout.autoflow)
const cellGroups = [
autoPositionCells(autoflowCells),
...staticLayouts.map((layout) => layout.cells),
...staticLayouts.map(layout => layout.cells),
]
const cells = translateCellGroups(cellGroups)
@ -71,7 +71,7 @@ function translateCellGroups(groups: LayoutCell[][]): LayoutCell[] {
}
function toCell(layoutCell: LayoutCell, source: Source): Cell {
const queries = layoutCell.queries.map((d) => toCellQuery(d, source))
const queries = layoutCell.queries.map(d => toCellQuery(d, source))
const cell = {
...NEW_DEFAULT_DASHBOARD_CELL,

View File

@ -11,7 +11,7 @@ export const linksFromHosts = (
hostNames: HostNames,
source: Source
): DashboardSwitcherLinks => {
const links = Object.values(hostNames).map((h) => {
const links = Object.values(hostNames).map(h => {
return {
key: h.name,
text: h.name,
@ -26,7 +26,7 @@ export const updateActiveHostLink = (
hostLinks: DashboardSwitcherLinks,
host: HostName
): DashboardSwitcherLinks => {
const active = hostLinks.links.find((link) => link.key === host.name)
const active = hostLinks.links.find(link => link.key === host.name)
return {...hostLinks, active}
}

View File

@ -184,15 +184,12 @@ export const RULE_MESSAGE_TEMPLATES: RuleMessageTemplate = {
},
}
export const RULE_MESSAGE_TEMPLATE_TEXTS = _.map(
RULE_MESSAGE_TEMPLATES,
(t) => {
const label = t.label
const templateRegexp = /((?:{{)([^{}]+)(?:}}))/g // matches {{*}} where star does not contain '{' or '}'
const match = templateRegexp.exec(label)
return match[2].trim()
}
)
export const RULE_MESSAGE_TEMPLATE_TEXTS = _.map(RULE_MESSAGE_TEMPLATES, t => {
const label = t.label
const templateRegexp = /((?:{{)([^{}]+)(?:}}))/g // matches {{*}} where star does not contain '{' or '}'
const match = templateRegexp.exec(label)
return match[2].trim()
})
// DEFAULT_HANDLERS are empty alert templates for handlers that don't exist in the kapacitor config
export const DEFAULT_HANDLERS: Handler[] = [

View File

@ -8,13 +8,13 @@ const ActiveKapacitorFromSources = (
return null
}
const ActiveSource = sources.find((s) => s.id === source.id)
const ActiveSource = sources.find(s => s.id === source.id)
if (!ActiveSource || !ActiveSource.kapacitors) {
return null
}
const {kapacitors} = ActiveSource
return kapacitors.find((k) => k.active) || kapacitors[0]
return kapacitors.find(k => k.active) || kapacitors[0]
}
export default ActiveKapacitorFromSources

View File

@ -22,8 +22,8 @@ const GLOBAL_FUNCTIONS = [
export const isValidTemplate = (template: string): boolean => {
if (
!!_.find(RULE_MESSAGE_TEMPLATE_TEXTS, (t) => t === template) ||
!!_.find(EXTRA_MESSAGE_VARIABLES, (t) => t === template)
!!_.find(RULE_MESSAGE_TEMPLATE_TEXTS, t => t === template) ||
!!_.find(EXTRA_MESSAGE_VARIABLES, t => t === template)
) {
return true
}
@ -49,7 +49,7 @@ export const isValidTemplate = (template: string): boolean => {
// check if we have a prefix that we can remove
const validPrefix = _.find(
GLOBAL_FUNCTIONS,
(t) =>
t =>
template.startsWith(t) &&
template.length > t.length &&
/\s/.test(template[t.length])
@ -77,7 +77,7 @@ export const isValidMessage = (message: string): boolean => {
match = templateRegexp.exec(message)
}
const isValid = _.every(matches, (m) => isValidTemplate(m))
const isValid = _.every(matches, m => isValidTemplate(m))
return isValid
}

View File

@ -25,7 +25,7 @@ interface Area {
h: number
}
const underlayCallback = (rule) => (
const underlayCallback = rule => (
canvas: CanvasRenderingContext2D,
area: Area,
dygraph: Dygraph

View File

@ -347,7 +347,7 @@ const getBackwardTableData = (state: State): TableData =>
*/
const combineTableData = (...tableDatas: TableData[]) => ({
columns: tableDatas[0].columns,
values: _.flatMap(tableDatas, (t) => t.values),
values: _.flatMap(tableDatas, t => t.values),
})
const getTimeRange = (state: State): TimeRange | null =>
@ -573,9 +573,9 @@ export const clearAllTimeBounds = () => (
dispatch(setNextTailLowerBound(undefined))
}
export const clearSearchData = (searchStatus: SearchStatus) => async (
dispatch
) => {
export const clearSearchData = (
searchStatus: SearchStatus
) => async dispatch => {
await dispatch(setSearchStatus(SearchStatus.Clearing))
dispatch(setHistogramData([]))
dispatch(clearAllTimeBounds())
@ -584,11 +584,11 @@ export const clearSearchData = (searchStatus: SearchStatus) => async (
await dispatch(setSearchStatus(searchStatus))
}
export const setTableCustomTimeAsync = (time: string) => async (dispatch) => {
export const setTableCustomTimeAsync = (time: string) => async dispatch => {
await dispatch(setTableCustomTime(time))
}
export const setTableRelativeTimeAsync = (time: number) => async (dispatch) => {
export const setTableRelativeTimeAsync = (time: number) => async dispatch => {
await dispatch(setTableRelativeTime(time))
}
@ -966,7 +966,7 @@ export const populateNamespacesAsync = (
if (currentNamespace) {
defaultNamespace = _.find(
namespaces,
(ns) =>
ns =>
ns.database === currentNamespace.database &&
ns.retentionPolicy === currentNamespace.retentionPolicy
)
@ -974,7 +974,7 @@ export const populateNamespacesAsync = (
if (!defaultNamespace && source.telegraf) {
defaultNamespace = _.find(
namespaces,
(ns) => ns.database === source.telegraf
ns => ns.database === source.telegraf
)
}
}

View File

@ -84,7 +84,7 @@ const removeFilter = (
const {id} = action.payload
const filters = _.filter(
_.get(state, 'filters', []),
(filter) => filter.id !== id
filter => filter.id !== id
)
return {...state, filters}
@ -106,7 +106,7 @@ const changeFilter = (
): LogsState => {
const {id, operator, value} = action.payload
const mappedFilters = _.map(_.get(state, 'filters', []), (f) => {
const mappedFilters = _.map(_.get(state, 'filters', []), f => {
if (f.id === id) {
return {...f, operator, value}
}

View File

@ -30,7 +30,7 @@ export const logConfigServerToUI = (
let severityFormat: SeverityFormatOptions
let severityLevelColors: SeverityLevelColor[]
const convertedColumns = sortedColumns.map((c) => {
const convertedColumns = sortedColumns.map(c => {
if (c.name === 'severity') {
severityFormat = getFormatFromColumn(c)
severityLevelColors = getLevelColorsFromColumn(c)
@ -48,7 +48,7 @@ export const logConfigServerToUI = (
}
export const sortColumns = (columns: ServerColumn[]): ServerColumn[] => {
return _.sortBy(columns, (c) => c.position)
return _.sortBy(columns, c => c.position)
}
export const columnServerToUI = (column: ServerColumn): LogsTableColumn => {
@ -76,7 +76,7 @@ export const getFormatFromColumn = (
let hasText = false
let hasIcon = false
column.encodings.forEach((e) => {
column.encodings.forEach(e => {
if (e.type === EncodingTypes.label) {
if (e.value === EncodingLabelOptions.icon) {
hasIcon = true
@ -99,8 +99,8 @@ export const getFormatFromColumn = (
export const getLevelColorsFromColumn = (
column: ServerColumn
): SeverityLevelColor[] => {
const colors = column.encodings.filter((e) => e.type === EncodingTypes.color)
return colors.map((c) => {
const colors = column.encodings.filter(e => e.type === EncodingTypes.color)
return colors.map(c => {
const level: SeverityLevelOptions = SeverityLevelOptions[c.name]
const color: SeverityColorOptions = SeverityColorOptions[c.value]
return {level, color}

View File

@ -22,7 +22,7 @@ export function fetchUntil<T>(
}
}
const fetchEachAsync = async (requestsIterator) => {
const fetchEachAsync = async requestsIterator => {
for (const response of requestsIterator) {
await response
}

View File

@ -138,12 +138,12 @@ export function buildInfiniteScrollWhereClause({
timeClauses.push(`time < '${upper}'`)
}
const tagClauses = _.keys(tags).map((k) => {
const tagClauses = _.keys(tags).map(k => {
const operator = areTagsAccepted ? '=' : '!='
if (tags[k].length > 1) {
const joinedOnOr = tags[k]
.map((v) => `"${k}"${operator}'${v}'`)
.map(v => `"${k}"${operator}'${v}'`)
.join(' OR ')
return `(${joinedOnOr})`
}
@ -330,14 +330,14 @@ export const parseHistogramQueryResponse = (
return acc
}
const timeColIndex = current.columns.findIndex((v) => v === 'time')
const countColIndex = current.columns.findIndex((v) => v === 'count')
const timeColIndex = current.columns.findIndex(v => v === 'time')
const countColIndex = current.columns.findIndex(v => v === 'count')
if (timeColIndex < 0 || countColIndex < 0) {
return acc
}
const vs = current.values.map((v) => {
const vs = current.values.map(v => {
const time = v[timeColIndex]
const value = v[countColIndex]

View File

@ -45,7 +45,7 @@ export const filtersToPattern = (filters: Filter[]): string => {
return null
}
const values = filters.map((f) => f.value).join('|')
const values = filters.map(f => f.value).join('|')
return `^(.*?)(${values})(.*)`
}

View File

@ -50,9 +50,7 @@ export const searchToFilters = (searchTerm: string): Filter[] => {
}
const termsToFilters = (terms: Term[]): Filter[] => {
return terms.map((t) =>
createAttributeFilter(t.attribute, t.term, termToOp(t))
)
return terms.map(t => createAttributeFilter(t.attribute, t.term, termToOp(t)))
}
const extractTerms = (searchTerms: string, rules: TermRule[]): Term[] => {
@ -81,7 +79,7 @@ const eatSpaces = (text: string): string => {
}
const readToken = (text: string, rules: TermRule[]): TokenLiteralMatch => {
const rule = rules.find((r) => text.match(new RegExp(r.pattern)) !== null)
const rule = rules.find(r => text.match(new RegExp(r.pattern)) !== null)
const term = new RegExp(rule.pattern).exec(text)
const literal = term[3]

View File

@ -68,7 +68,7 @@ export const header = (
return ''
}
const headerOption = _.find(headerOptions, (h) => h.internalName === key)
const headerOption = _.find(headerOptions, h => h.internalName === key)
return _.get(headerOption, 'displayName') || _.capitalize(key)
}
@ -124,7 +124,7 @@ export const getFixedColumnsTotalWidth = (
const columns = getColumnsFromData(data)
return columns.reduce((acc, col) => {
const colConfig = tableColumns.find((c) => c.internalName === col)
const colConfig = tableColumns.find(c => c.internalName === col)
const isColVisible = colConfig && colConfig.visible
if (col === 'message' || col === 'time' || !isColVisible) {
return acc
@ -186,7 +186,7 @@ export const applyChangesToTableData = (
const timestampNsInMsColumnIndex = _.indexOf(columns, TIMESTAMP_NSINMS)
if (timeColumnIndex >= 0 && timestampColumnIndex >= 0) {
// modify existing data to save memory
values.forEach((row) => {
values.forEach(row => {
if (row[timestampColumnIndex] === null) {
row[timestampColumnIndex] = (row[timeColumnIndex] as number) * 1000000
} else if (timestampNsInMsColumnIndex >= 0) {
@ -232,7 +232,7 @@ export const findTimeOptionRow = (
const selectedTime = new Date(timeOption).valueOf()
const timeColumn = forward.columns.indexOf('time')
const tableData = [...forward.values, ...backward.values]
const rowIndex = tableData.findIndex((row) => row[timeColumn] <= selectedTime)
const rowIndex = tableData.findIndex(row => row[timeColumn] <= selectedTime)
if (rowIndex < 0) {
return defaultIndex

View File

@ -253,7 +253,7 @@ export const setDisplaySetting = (
export const addAnnotationAsync = (
createUrl: string,
annotation: Annotation
) => async (dispatch) => {
) => async dispatch => {
dispatch(addAnnotation(annotation))
try {
@ -294,9 +294,9 @@ export const getAnnotationsAsync = (
dispatch(setAnnotations(annotations))
}
export const deleteAnnotationAsync = (annotation: Annotation) => async (
dispatch
) => {
export const deleteAnnotationAsync = (
annotation: Annotation
) => async dispatch => {
try {
dispatch(deleteAnnotation(annotation))
await api.deleteAnnotation(annotation)
@ -306,9 +306,9 @@ export const deleteAnnotationAsync = (annotation: Annotation) => async (
}
}
export const updateAnnotationAsync = (annotation: Annotation) => async (
dispatch
) => {
export const updateAnnotationAsync = (
annotation: Annotation
) => async dispatch => {
try {
await api.updateAnnotation(annotation)
dispatch(updateAnnotation(annotation))
@ -348,7 +348,7 @@ export const deleteTagFilterAsync = (
indexURL: string,
dashboardID: string,
tagFilter: TagFilter
) => async (dispatch) => {
) => async dispatch => {
try {
dispatch(deleteTagFilter(dashboardID, tagFilter))
await dispatch(getAnnotationsAsync(indexURL, dashboardID))
@ -358,19 +358,20 @@ export const deleteTagFilterAsync = (
}
}
export const fetchAndSetTagKeys = (source: string) => async (dispatch) => {
export const fetchAndSetTagKeys = (source: string) => async dispatch => {
const query = 'SHOW TAG KEYS ON chronograf FROM annotations'
const resp = await proxy({query, source})
const tagKeys = parseMetaQuery(query, resp.data).filter(
(keys) => !BLACKLISTED_KEYS.includes(keys)
keys => !BLACKLISTED_KEYS.includes(keys)
)
dispatch(setTagKeys(tagKeys))
}
export const fetchAndSetTagValues = (source: string, tagKey: string) => async (
dispatch
) => {
export const fetchAndSetTagValues = (
source: string,
tagKey: string
) => async dispatch => {
const query = `SHOW TAG VALUES ON chronograf FROM annotations WITH KEY = "${tagKey}"`
const resp = await proxy({query, source})
const tagValues = parseMetaQuery(query, resp.data)

View File

@ -154,7 +154,7 @@ export const meChangeOrganizationAsync = (
try {
const {data: me, auth, logoutLink} = await updateMeAJAX(url, organization)
const currentRole = me.roles.find(
(r) => r.organization === me.currentOrganization.id
r => r.organization === me.currentOrganization.id
)
dispatch(
notify(

View File

@ -133,11 +133,11 @@ export type FetchAllFluxServicesAsync = (
sources: Source[]
) => (dispatch) => Promise<void>
export const fetchAllFluxServicesAsync: FetchAllFluxServicesAsync = (
sources
) => async (dispatch): Promise<void> => {
export const fetchAllFluxServicesAsync: FetchAllFluxServicesAsync = sources => async (
dispatch
): Promise<void> => {
const allServicesForSources: Array<Promise<Service[]>> = sources.map(
async (source) => {
async source => {
try {
return getServicesAJAX(source.links.services)
} catch (err) {
@ -149,7 +149,7 @@ export const fetchAllFluxServicesAsync: FetchAllFluxServicesAsync = (
try {
const sourceServices = await Promise.all(allServicesForSources)
const flat = sourceServices.reduce((acc, cur) => {
return [...acc, ...cur.filter((s) => s.type === 'flux')]
return [...acc, ...cur.filter(s => s.type === 'flux')]
})
dispatch(loadServices(flat))
} catch (err) {
@ -162,12 +162,12 @@ export const fetchAllFluxServicesAsync: FetchAllFluxServicesAsync = (
export type FetchFluxServicesForSourceAsync = (
source: Source
) => (dispatch) => Promise<void>
export const fetchFluxServicesForSourceAsync: FetchFluxServicesForSourceAsync = (
source
) => async (dispatch): Promise<void> => {
export const fetchFluxServicesForSourceAsync: FetchFluxServicesForSourceAsync = source => async (
dispatch
): Promise<void> => {
try {
const services = await getServicesAJAX(source.links.services)
const fluxServices = services.filter((s) => s.type === 'flux')
const fluxServices = services.filter(s => s.type === 'flux')
dispatch(loadServices(fluxServices))
} catch (err) {
console.error(err.data)

View File

@ -145,7 +145,7 @@ export const removeAndLoadSources = (source: Source) => async (
getState
): Promise<void> => {
const {sources = []} = getState()
const filteredSources = sources.filter((s) => s.id !== source.id)
const filteredSources = sources.filter(s => s.id !== source.id)
dispatch(loadSources(filteredSources))
@ -174,9 +174,7 @@ export type FetchKapacitorsAsync = (
source: Source
) => (dispatch) => Promise<void>
export const fetchKapacitorsAsync: FetchKapacitorsAsync = (source) => async (
dispatch
) => {
export const fetchKapacitorsAsync: FetchKapacitorsAsync = source => async dispatch => {
try {
const kapacitors = await getKapacitorsAJAX(source)
dispatch(fetchKapacitors(source, kapacitors))
@ -185,9 +183,7 @@ export const fetchKapacitorsAsync: FetchKapacitorsAsync = (source) => async (
}
}
export const fetchKapacitorsAsyncNoNotify: FetchKapacitorsAsync = (
source
) => async (dispatch) => {
export const fetchKapacitorsAsyncNoNotify: FetchKapacitorsAsync = source => async dispatch => {
const kapacitors = await getKapacitorsAJAX(source)
dispatch(fetchKapacitors(source, kapacitors))
}

View File

@ -32,7 +32,7 @@ export const visibleAnnotations = (
return []
}
return annotations.filter((a) => {
return annotations.filter(a => {
if (a.startTime === null || a.endTime === null) {
return false
}

View File

@ -20,7 +20,7 @@ const getRetentionPolices = async (proxy, databases) => {
const rp = rps[j]
const {retentionPolicies} = showRetentionPoliciesParser(rp)
const dbrp = retentionPolicies.map((r) => ({
const dbrp = retentionPolicies.map(r => ({
database,
retentionPolicy: r.name,
}))

View File

@ -5,7 +5,7 @@ const DEFAULT_ENVS = {
hostPageDisabled: false,
}
export const getEnv = async (url) => {
export const getEnv = async url => {
try {
const {data} = await AJAX({
method: 'GET',

View File

@ -159,7 +159,7 @@ export const proxy = async (source: Source, script: string) => {
}
}
const handleError = (error) => {
const handleError = error => {
console.error('Problem fetching data', error)
throw _.get(error, 'headers.x-influx-error', false) ||

View File

@ -104,7 +104,7 @@ export const getActiveKapacitor = async (
method: 'GET',
})
const activeKapacitor = data.kapacitors.find((k) => k.active)
const activeKapacitor = data.kapacitors.find(k => k.active)
return activeKapacitor || data.kapacitors[0]
} catch (error) {
console.error(error)
@ -278,7 +278,7 @@ export const testAlertOutput = async (
const {
data: {services},
} = await kapacitorProxy(kapacitor, 'GET', '/kapacitor/v1/service-tests')
const service = services.find((s) => s.name === outputName)
const service = services.find(s => s.name === outputName)
let body = {}
if (options) {

View File

@ -27,15 +27,15 @@ export function executeQueries(
templates: Template[],
uuid?: string
): Promise<QueryResult[]> {
return new Promise((resolve) => {
return new Promise(resolve => {
const results = []
let counter = queries.length
for (let i = 0; i < queries.length; i++) {
executeQuery(source, queries[i], templates, uuid)
.then((result) => (results[i] = {value: result, error: null}))
.catch((result) => (results[i] = {value: null, error: result}))
.then(result => (results[i] = {value: result, error: null}))
.catch(result => (results[i] = {value: null, error: result}))
.then(() => {
counter -= 1

View File

@ -9,7 +9,7 @@ import {
import {CellType} from 'src/types/dashboards'
const getLegibleTextColor = (bgColorHex) => {
const getLegibleTextColor = bgColorHex => {
const darkText = '#292933'
const lightText = '#ffffff'
@ -21,16 +21,16 @@ const getLegibleTextColor = (bgColorHex) => {
}
const findNearestCrossedThreshold = (colors, lastValue) => {
const sortedColors = _.sortBy(colors, (color) => Number(color.value))
const sortedColors = _.sortBy(colors, color => Number(color.value))
const nearestCrossedThreshold = sortedColors
.filter((color) => lastValue >= color.value)
.filter(color => lastValue >= color.value)
.pop()
return nearestCrossedThreshold
}
export const stringifyColorValues = (colors) => {
return colors.map((color) => ({...color, value: `${color.value}`}))
export const stringifyColorValues = colors => {
return colors.map(color => ({...color, value: `${color.value}`}))
}
export const generateThresholdsListHexs = ({
@ -52,9 +52,7 @@ export const generateThresholdsListHexs = ({
}
// baseColor is expected in all cases
const baseColor = colors.find(
(color) => (color.id = THRESHOLD_TYPE_BASE)
) || {
const baseColor = colors.find(color => (color.id = THRESHOLD_TYPE_BASE)) || {
hex: defaultColoring.textColor,
}
@ -71,7 +69,7 @@ export const generateThresholdsListHexs = ({
// When there is only a base color and it's applied to the text
const shouldColorizeText = !!colors.find(
(color) => color.type === THRESHOLD_TYPE_TEXT
color => color.type === THRESHOLD_TYPE_TEXT
)
if (shouldColorizeText && colors.length === 1) {
return baseColor

View File

@ -200,7 +200,7 @@ export const LINE_COLOR_SCALES = [
LINE_COLORS_E,
LINE_COLORS_F,
LINE_COLORS_G,
].map((colorScale) => {
].map(colorScale => {
const name = colorScale[0].name
const colors = colorScale
const id = colorScale[0].id
@ -218,7 +218,7 @@ export const getLineColors = (
}
const testColorsTypes =
colors.filter((color) => color.type === COLOR_TYPE_SCALE).length ===
colors.filter(color => color.type === COLOR_TYPE_SCALE).length ===
colors.length
return testColorsTypes ? colors : DEFAULT_LINE_COLORS
@ -229,7 +229,7 @@ export const getLineColorsHexes = (
numSeries: number
): string[] => {
const validatedColors = getLineColors(colors, numSeries) // ensures safe defaults
const colorsHexArray = validatedColors.map((color) => color.hex)
const colorsHexArray = validatedColors.map(color => color.hex)
if (numSeries === 1 || numSeries === 0) {
return [colorsHexArray[0]]

View File

@ -481,12 +481,12 @@ export const interval: Template = {
export const TEMPLATES: Template[] = [interval]
export const IS_STATIC_LEGEND = (legend) =>
export const IS_STATIC_LEGEND = legend =>
_.get(legend, 'type', false) === 'static'
export const linksLink = '/chronograf/v1'
export const cellSupportsAnnotations = (cellType) => {
export const cellSupportsAnnotations = cellType => {
const supportedTypes = [
CellType.Line,
CellType.Bar,
@ -494,7 +494,7 @@ export const cellSupportsAnnotations = (cellType) => {
CellType.Stacked,
CellType.StepPlot,
]
return !!supportedTypes.find((type) => type === cellType)
return !!supportedTypes.find(type => type === cellType)
}
export const NOTIFICATION_TRANSITION = 250

View File

@ -119,7 +119,7 @@ export const DEFAULT_THRESHOLDS_LIST_COLORS = [
},
]
export const getThresholdsListColors = (colors) => {
export const getThresholdsListColors = colors => {
const type = getThresholdsListType(colors)
if (!colors || colors.length === 0) {
@ -143,7 +143,7 @@ export const getThresholdsListColors = (colors) => {
let containsBaseColor = false
const formattedColors = colors.map((color) => {
const formattedColors = colors.map(color => {
if (color.id === THRESHOLD_TYPE_BASE) {
// Check for existance of base color
containsBaseColor = true
@ -161,7 +161,7 @@ export const getThresholdsListColors = (colors) => {
return containsBaseColor ? formattedColors : formattedColorsWithBase
}
const getThresholdsListType = (colors) => {
const getThresholdsListType = colors => {
const type = _.get(colors, ['0', 'type'], false)
if (type && _.includes([THRESHOLD_TYPE_TEXT, THRESHOLD_TYPE_BG], type)) {
@ -171,7 +171,7 @@ const getThresholdsListType = (colors) => {
return THRESHOLD_TYPE_TEXT
}
export const getGaugeColors = (colors) => {
export const getGaugeColors = colors => {
if (!colors || colors.length < MIN_THRESHOLDS) {
return DEFAULT_GAUGE_COLORS
}
@ -192,8 +192,8 @@ export const getGaugeColors = (colors) => {
}
// Gauge colors should have a type of min, any number of thresholds, and a max
const formattedColors = _.sortBy(colors, (color) => Number(color.value)).map(
(color) => ({
const formattedColors = _.sortBy(colors, color => Number(color.value)).map(
color => ({
...color,
value: Number(color.value),
type: COLOR_TYPE_THRESHOLD,
@ -206,6 +206,6 @@ export const getGaugeColors = (colors) => {
return formattedColors
}
export const stringifyColorValues = (colors) => {
return colors.map((color) => ({...color, value: `${color.value}`}))
export const stringifyColorValues = colors => {
return colors.map(color => ({...color, value: `${color.value}`}))
}

View File

@ -97,5 +97,5 @@ export const DEFAULT_TIME_RANGE = {
}
export const STATUS_PAGE_TIME_RANGE = timeRanges.find(
(tr) => tr.lower === nowMinus30d
tr => tr.lower === nowMinus30d
)

View File

@ -32,7 +32,7 @@ export const LINE_COLORS = [
export const SMALL_CELL_HEIGHT = 2
export const darkenColor = (colorStr) => {
export const darkenColor = colorStr => {
// Defined in dygraph-utils.js
const color = toRGB(colorStr)
color.r = Math.floor((255 + color.r) / 2)
@ -42,7 +42,7 @@ export const darkenColor = (colorStr) => {
}
// Bar Graph code below is adapted from http://dygraphs.com/tests/plotters.html
export const barPlotter = (e) => {
export const barPlotter = e => {
// We need to handle all the series simultaneously.
if (e.seriesIndex !== 0) {
return
@ -179,7 +179,7 @@ export const removeMeasurement = (label = '') => {
export const hasherino = (str, len) =>
str
.split('')
.map((char) => char.charCodeAt(0))
.map(char => char.charCodeAt(0))
.reduce((hash, code) => hash + code, 0) % len
export const LABEL_WIDTH = 44

View File

@ -23,14 +23,14 @@ export function getMinDurationFromAST(ast: any) {
// 4. Take the minimum duration
//
const times = allRangeTimes(ast)
const starts = times.map((t) => t[0])
const stops = times.map((t) => t[1])
const crossProduct = starts.map((start) => stops.map((stop) => [start, stop]))
const starts = times.map(t => t[0])
const stops = times.map(t => t[1])
const crossProduct = starts.map(start => stops.map(stop => [start, stop]))
const durations = []
.concat(...crossProduct)
.map(([start, stop]) => stop - start)
.filter((d) => d > 0)
.filter(d => d > 0)
const result = Math.min(...durations)
@ -110,7 +110,7 @@ interface DurationBinaryExpression {
export function allRangeTimes(ast: any): Array<[number, number]> {
const now = Date.now()
return findNodes(isRangeNode, ast).map((node) => rangeTimes(ast, node, now))
return findNodes(isRangeNode, ast).map(node => rangeTimes(ast, node, now))
}
/*
@ -126,11 +126,11 @@ function rangeTimes(
const properties = rangeNode.arguments[0].properties
// The `start` argument is required
const startProperty = properties.find((p) => p.key.name === 'start')
const startProperty = properties.find(p => p.key.name === 'start')
const start = propertyTime(ast, startProperty.value, now)
// The `end` argument to a `range` call is optional, and defaults to now
const endProperty = properties.find((p) => p.key.name === 'stop')
const endProperty = properties.find(p => p.key.name === 'stop')
const end = endProperty ? propertyTime(ast, endProperty.value, now) : now
if (isNaN(start) || isNaN(end)) {
@ -195,7 +195,7 @@ function durationDuration(durationLiteral: DurationLiteral): number {
given `name`.
*/
function resolveDeclaration(ast: any, name: string): RangeCallPropertyValue {
const isDeclarator = (node) => {
const isDeclarator = node => {
return (
get(node, 'type') === 'VariableAssignment' &&
get(node, 'id.name') === name

View File

@ -7,8 +7,8 @@ export const extractImports = async (
const ast = await getAST({url, body: query})
const {imports, body} = ast.files[0]
const importStatements = (imports || [])
.map((i) => i.location.source)
.map(i => i.location.source)
.join('\n')
const bodyStatements = (body || []).map((b) => b.location.source).join('\n')
const bodyStatements = (body || []).map(b => b.location.source).join('\n')
return {imports: importStatements, body: bodyStatements}
}

View File

@ -26,7 +26,7 @@ export const parseTablesByTime = (
const allColumnNames = []
const nonNumericColumns = []
const tablesByTime = tables.map((table) => {
const tablesByTime = tables.map(table => {
const header = table.data[0] as string[]
const columnNames: {[k: number]: string} = {}

View File

@ -32,10 +32,10 @@ const parseChunks = (response: string): string[] => {
export const parseTables = (responseChunk: string): FluxTable[] => {
const lines = responseChunk.split('\n')
const annotationLines: string = lines
.filter((line) => line.startsWith('#'))
.filter(line => line.startsWith('#'))
.join('\n')
const nonAnnotationLines: string = lines
.filter((line) => !line.startsWith('#'))
.filter(line => !line.startsWith('#'))
.join('\n')
if (_.isEmpty(annotationLines)) {
@ -56,8 +56,8 @@ export const parseTables = (responseChunk: string): FluxTable[] => {
throw new Error(_.get(nonAnnotationData, '1.1'))
}
const tableColIndex = headerRow.findIndex((h) => h === 'table')
const timeColIndex = headerRow.findIndex((h) => h === '_time')
const tableColIndex = headerRow.findIndex(h => h === 'table')
const timeColIndex = headerRow.findIndex(h => h === '_time')
if (!timeColIndex) {
throw new Error('Could not find time Column')
@ -65,12 +65,12 @@ export const parseTables = (responseChunk: string): FluxTable[] => {
// Group rows by their table id
const tablesData: Array<Array<Array<string | number>>> = Object.values(
_.groupBy(nonAnnotationData.slice(1), (row) => row[tableColIndex])
_.groupBy(nonAnnotationData.slice(1), row => row[tableColIndex])
)
const groupRow = annotationData.find((row) => row[0] === '#group')
const defaultsRow = annotationData.find((row) => row[0] === '#default')
const dataTypeRow = annotationData.find((row) => row[0] === '#datatype')
const groupRow = annotationData.find(row => row[0] === '#group')
const defaultsRow = annotationData.find(row => row[0] === '#default')
const dataTypeRow = annotationData.find(row => row[0] === '#datatype')
// groupRow = ['#group', 'false', 'true', 'true', 'false']
const groupKeyIndices = groupRow.reduce((acc, value, i) => {
@ -81,7 +81,7 @@ export const parseTables = (responseChunk: string): FluxTable[] => {
return acc
}, [])
const tables = tablesData.map((tableData) => {
const tables = tablesData.map(tableData => {
const dataRow = _.get(tableData, '0', defaultsRow)
const groupKey = groupKeyIndices.reduce((acc, i) => {
return {...acc, [headerRow[i]]: _.get(dataRow, i, '')}
@ -125,10 +125,10 @@ interface ParseResponseRawResult {
export const parseResponseRaw = (response: string): ParseResponseRawResult => {
const chunks = parseChunks(response)
const parsedChunks = chunks.map((c) => Papa.parse(c).data)
const parsedChunks = chunks.map(c => Papa.parse(c).data)
const maxColumnCount =
parsedChunks.length > 0
? Math.max(...parsedChunks.map((c) => c[0].length))
? Math.max(...parsedChunks.map(c => c[0].length))
: 0
const data = []

View File

@ -11,20 +11,18 @@ const parseValuesColumn = (resp: string): string[] => {
}
const tags = results.reduce<string[]>((acc, result: FluxTable) => {
const colIndex = result.data[0].findIndex((header) => header === '_value')
const colIndex = result.data[0].findIndex(header => header === '_value')
if (colIndex === -1) {
return [...acc]
}
const resultTags = result.data
.slice(1)
.map((row) => row[colIndex] as string)
const resultTags = result.data.slice(1).map(row => row[colIndex] as string)
return [...acc, ...resultTags]
}, [])
return _.sortBy(tags, (t) => t.toLocaleLowerCase())
return _.sortBy(tags, t => t.toLocaleLowerCase())
}
export const parseFieldsByMeasurements = (
@ -41,11 +39,9 @@ export const parseFieldsByMeasurements = (
return results.reduce(
(acc, result: FluxTable) => {
const fieldIndex = result.data[0].findIndex(
(header) => header === '_field'
)
const fieldIndex = result.data[0].findIndex(header => header === '_field')
const measurementIndex = result.data[0].findIndex(
(header) => header === '_measurement'
header => header === '_measurement'
)
if (fieldIndex === -1) {
@ -54,7 +50,7 @@ export const parseFieldsByMeasurements = (
const data = result.data.slice(1)
data.forEach((row) => {
data.forEach(row => {
const field = row[fieldIndex]
if (!acc.fields.includes(field)) {
acc.fields.push(field)

View File

@ -4,7 +4,7 @@ import {RuleValues} from 'src/types'
const ADD_FACTOR = 1.1
const SUB_FACTOR = 0.9
const checkNumeric = (num) => (isFinite(num) ? num : null)
const checkNumeric = num => (isFinite(num) ? num : null)
const considerEmpty = (userNumber, num) => {
if (userNumber) {
@ -29,10 +29,10 @@ const getRange = (
const userMin = checkNumeric(uMin)
const userMax = checkNumeric(uMax)
const addPad = (bigNum) => bigNum.times(ADD_FACTOR).toNumber()
const subPad = (bigNum) => bigNum.times(SUB_FACTOR).toNumber()
const addPad = bigNum => bigNum.times(ADD_FACTOR).toNumber()
const subPad = bigNum => bigNum.times(SUB_FACTOR).toNumber()
const pad = (v) => {
const pad = v => {
if (v === null || v === '' || !isFinite(v)) {
return null
}
@ -95,7 +95,7 @@ const getRange = (
return [min, max]
}
const coerceToNum = (str) => (str ? +str : null)
const coerceToNum = str => (str ? +str : null)
export const getStackedRange = (bounds = [null, null]): [number, number] => [
coerceToNum(bounds[0]),
coerceToNum(bounds[1]),

View File

@ -11,7 +11,7 @@ import {TimeSeriesResponse} from 'src/types/series'
const parsers = {
databases,
measurements: (data) => {
measurements: data => {
const {errors, measurementSets} = measurements(data)
return {
errors,

View File

@ -18,7 +18,7 @@ const parseShowSeries = (response): ParseShowSeriesResponse => {
return {errors: [], series: []}
}
const series = seriesValues.map((s) => s[0])
const series = seriesValues.map(s => s[0])
return {series, errors: []}
}

View File

@ -5,7 +5,7 @@ import {Me} from 'src/types/auth'
export const getMeRole = (me: Me): string => {
const currentRoleOrg = me.roles.find(
(role) => me.currentOrganization.id === role.organization
role => me.currentOrganization.id === role.organization
)
const currentRole = _.get(currentRoleOrg, 'name', MEMBER_ROLE)

View File

@ -18,7 +18,7 @@ export const notifications = (state = initialState, action: Action) => {
case 'DISMISS_NOTIFICATION': {
const {id} = action.payload
return state.filter((n) => n.id !== id)
return state.filter(n => n.id !== id)
}
}

View File

@ -16,13 +16,13 @@ const servicesReducer = (state = initialState, action: Action): Service[] => {
case 'DELETE_SERVICE': {
const {service} = action.payload
const services = state.filter((s) => s.id !== service.id)
const services = state.filter(s => s.id !== service.id)
return services
}
case 'UPDATE_SERVICE': {
const {service} = action.payload
const newState = state.map((s) => {
const newState = state.map(s => {
if (s.id === service.id) {
return {...s, ...service}
}
@ -36,13 +36,13 @@ const servicesReducer = (state = initialState, action: Action): Service[] => {
case 'SET_ACTIVE_SERVICE': {
const {source, service} = action.payload
let otherServices = []
const currentServices = state.filter((s) => {
const currentServices = state.filter(s => {
if (s.sourceID !== source.id) {
otherServices = [...otherServices, s]
}
return s.sourceID === source.id
})
const updatedServices = currentServices.map((s) => {
const updatedServices = currentServices.map(s => {
if (s.sourceID === source.id) {
const metadata = {active: s.id === service.id}
s.metadata = metadata

View File

@ -12,9 +12,9 @@ const sourcesReducer = (state = initialState, action: Action): Source[] => {
case 'SOURCE_UPDATED': {
const {source} = action.payload
const updatedIndex = state.findIndex((s) => s.id === source.id)
const updatedIndex = state.findIndex(s => s.id === source.id)
const updatedSources = source.default
? state.map((s) => {
? state.map(s => {
s.default = false
return s
})
@ -26,7 +26,7 @@ const sourcesReducer = (state = initialState, action: Action): Source[] => {
case 'SOURCE_ADDED': {
const {source} = action.payload
const updatedSources = source.default
? state.map((s) => {
? state.map(s => {
s.default = false
return s
})
@ -36,7 +36,7 @@ const sourcesReducer = (state = initialState, action: Action): Source[] => {
case 'LOAD_KAPACITORS': {
const {source, kapacitors} = action.payload
const sourceIndex = state.findIndex((s) => s.id === source.id)
const sourceIndex = state.findIndex(s => s.id === source.id)
const updatedSources = _.cloneDeep(state)
if (updatedSources[sourceIndex]) {
updatedSources[sourceIndex].kapacitors = kapacitors
@ -47,7 +47,7 @@ const sourcesReducer = (state = initialState, action: Action): Source[] => {
case 'SET_ACTIVE_KAPACITOR': {
const {kapacitor} = action.payload
const updatedSources = _.cloneDeep(state)
updatedSources.forEach((source) => {
updatedSources.forEach(source => {
source.kapacitors.forEach((k, i) => {
source.kapacitors[i].active = k.id === kapacitor.id
})
@ -58,10 +58,10 @@ const sourcesReducer = (state = initialState, action: Action): Source[] => {
case 'DELETE_KAPACITOR': {
const {kapacitor} = action.payload
const updatedSources = _.cloneDeep(state)
updatedSources.forEach((source) => {
updatedSources.forEach(source => {
const index = _.findIndex<Kapacitor>(
source.kapacitors,
(k) => k.id === kapacitor.id
k => k.id === kapacitor.id
)
if (index >= 0) {

View File

@ -21,7 +21,7 @@ export const getSelectedAnnotations = createSelector(
return []
}
return Object.values<Annotation>(annotationsById).filter((a) => !!a)
return Object.values<Annotation>(annotationsById).filter(a => !!a)
}
)
@ -32,16 +32,16 @@ const getTagFiltersById = (
export const getTagFilters = createSelector(
getTagFiltersById,
(tagFiltersById) => {
return Object.values(tagFiltersById || {}).filter((v) => !!v)
tagFiltersById => {
return Object.values(tagFiltersById || {}).filter(v => !!v)
}
)
export const getTagsFromTagFilters = createSelector(
getTagFilters,
(tagFilters) => {
tagFilters => {
return tagFilters
.filter((t) => t.filterType === TagFilterType.Equals)
.filter(t => t.filterType === TagFilterType.Equals)
.reduce(
(acc, t) => ({
...acc,

View File

@ -229,22 +229,22 @@ export class TimeMachineContainer extends Container<TimeMachineState> {
}
public handleToggleField = (queryID: string, fieldFunc: Field) => {
return this.updateQueryDrafts(queryID, (q) => ({
return this.updateQueryDrafts(queryID, q => ({
...toggleField(q, fieldFunc),
rawText: null,
}))
}
public handleGroupByTime = (queryID: string, time: string) => {
return this.updateQueryDrafts(queryID, (q) => groupByTime(q, time))
return this.updateQueryDrafts(queryID, q => groupByTime(q, time))
}
public handleFill = (queryID: string, value: string) => {
return this.updateQueryDrafts(queryID, (q) => fill(q, value))
return this.updateQueryDrafts(queryID, q => fill(q, value))
}
public handleRemoveFuncs = (queryID: string, fields: Field[]) => {
return this.updateQueryDrafts(queryID, (q) => removeFuncs(q, fields))
return this.updateQueryDrafts(queryID, q => removeFuncs(q, fields))
}
public handleApplyFuncsToField = (
@ -252,35 +252,35 @@ export class TimeMachineContainer extends Container<TimeMachineState> {
fieldFunc: ApplyFuncsToFieldArgs,
groupBy?: GroupBy
) => {
return this.updateQueryDrafts(queryID, (q) =>
return this.updateQueryDrafts(queryID, q =>
applyFuncsToField(q, fieldFunc, groupBy)
)
}
public handleChooseTag = (queryID: string, tag: Tag) => {
return this.updateQueryDrafts(queryID, (q) => chooseTag(q, tag))
return this.updateQueryDrafts(queryID, q => chooseTag(q, tag))
}
public handleChooseNamespace = (
queryID: string,
options: {database: string; retentionPolicy: string}
) => {
return this.updateQueryDrafts(queryID, (q) => chooseNamespace(q, options))
return this.updateQueryDrafts(queryID, q => chooseNamespace(q, options))
}
public handleChooseMeasurement = (queryID: string, measurement: string) => {
return this.updateQueryDrafts(queryID, (q) => ({
return this.updateQueryDrafts(queryID, q => ({
...chooseMeasurement(q, measurement),
rawText: q.rawText || '',
}))
}
public handleGroupByTag = (queryID: string, tagKey: string) => {
return this.updateQueryDrafts(queryID, (q) => groupByTag(q, tagKey))
return this.updateQueryDrafts(queryID, q => groupByTag(q, tagKey))
}
public handleToggleTagAcceptance = (queryID: string) => {
return this.updateQueryDrafts(queryID, (q) => toggleTagAcceptance(q))
return this.updateQueryDrafts(queryID, q => toggleTagAcceptance(q))
}
public handleAddInitialField = (
@ -288,17 +288,17 @@ export class TimeMachineContainer extends Container<TimeMachineState> {
field: Field,
groupBy: GroupBy
) => {
return this.updateQueryDrafts(queryID, (q) =>
return this.updateQueryDrafts(queryID, q =>
addInitialField(q, field, groupBy)
)
}
public handleEditQueryStatus = (queryID: string, status: Status) => {
return this.updateQueryDrafts(queryID, (q) => ({...q, status}))
return this.updateQueryDrafts(queryID, q => ({...q, status}))
}
public handleTimeShift = (queryID: string, shift: TimeShift) => {
return this.updateQueryDrafts(queryID, (q) => timeShift(q, shift))
return this.updateQueryDrafts(queryID, q => timeShift(q, shift))
}
public handleAddQuery = (): Promise<void> => {
@ -312,9 +312,7 @@ export class TimeMachineContainer extends Container<TimeMachineState> {
public handleDeleteQuery = (queryID: string) => {
const {queryDrafts} = this.state
const updatedQueryDrafts = queryDrafts.filter(
(query) => query.id !== queryID
)
const updatedQueryDrafts = queryDrafts.filter(query => query.id !== queryID)
return this.setAndPersistState({queryDrafts: updatedQueryDrafts})
}
@ -340,12 +338,10 @@ export class TimeMachineContainer extends Container<TimeMachineState> {
public handleUpdateThresholdsListType = (
thresholdsListType: ThresholdType
) => {
const thresholdsListColors = this.state.thresholdsListColors.map(
(color) => ({
...color,
type: thresholdsListType,
})
)
const thresholdsListColors = this.state.thresholdsListColors.map(color => ({
...color,
type: thresholdsListType,
}))
return this.setAndPersistState({
thresholdsListType,
thresholdsListColors,
@ -385,7 +381,7 @@ export class TimeMachineContainer extends Container<TimeMachineState> {
nextQueryConfigFn: (q: QueryConfig) => QueryConfig
) => {
const {queryDrafts} = this.state
const updatedQueryDrafts = queryDrafts.map((query) => {
const updatedQueryDrafts = queryDrafts.map(query => {
if (query.id === queryID) {
const nextQueryConfig = nextQueryConfigFn(query.queryConfig)

View File

@ -18,7 +18,7 @@ export const downloadInfluxQLCSV = async (
timeZone: TimeZones = TimeZones.UTC
): Promise<void> => {
const responses = await Promise.all(
queries.map((query) =>
queries.map(query =>
executeInfluxQLQuery(query.queryConfig.source, query, templates)
)
)
@ -54,7 +54,7 @@ const timeseriesToCSV = async (
responses: TimeSeriesResponse[],
timeZone: TimeZones
): Promise<string> => {
const wrapped = responses.map((response) => ({response}))
const wrapped = responses.map(response => ({response}))
const tableResponse = await timeSeriesToTableGraph(wrapped)
const table = tableResponse.data

View File

@ -18,7 +18,7 @@ export async function fetchDBsToRPs(proxyLink: string): Promise<DBsToRPs> {
const dbs = parseMetaQuery(dbsQuery, dbsResp.data).sort()
const rpsQuery = dbs
.map((db) => `SHOW RETENTION POLICIES ON "${db}"`)
.map(db => `SHOW RETENTION POLICIES ON "${db}"`)
.join('; ')
const rpsResp = await proxy({source: proxyLink, query: rpsQuery})
@ -26,7 +26,7 @@ export async function fetchDBsToRPs(proxyLink: string): Promise<DBsToRPs> {
const dbsToRPs: DBsToRPs = dbs.reduce((acc, db, i) => {
const series = rpsResp.data.results[i].series[0]
const namesIndex = series.columns.indexOf('name')
const rpNames = series.values.map((row) => row[namesIndex])
const rpNames = series.values.map(row => row[namesIndex])
return {...acc, [db]: rpNames}
}, {})
@ -114,7 +114,7 @@ export function renderScript(
if (selectedFields.length) {
const fieldsPredicate = selectedFields
.map((f) => `r._field == "${f}"`)
.map(f => `r._field == "${f}"`)
.join(' or ')
filterPredicate += ` and (${fieldsPredicate})`

View File

@ -74,7 +74,7 @@ function initialQueryDrafts(cell: Cell | NewDefaultCell): CellQuery[] {
return [defaultQueryDraft(QueryType.InfluxQL, cell.queries[0].source)]
}
return queries.map((q) => {
return queries.map(q => {
const id = uuid.v4()
const queryConfig = {
...q.queryConfig,

View File

@ -58,7 +58,7 @@ export const fetchJSONFeedAsync = (url: string) => async (
// decode HTML entities from response text
const decodedData = {
...data,
items: data.items.map((item) => {
items: data.items.map(item => {
item.title = he.decode(item.title)
item.content_text = he.decode(item.content_text)
return item

View File

@ -207,7 +207,7 @@ export const RESERVED_TEMPLATE_NAMES = [
export const MATCH_INCOMPLETE_TEMPLATES = /:[\w-]*/g
export const applyMasks = (query) => {
export const applyMasks = query => {
const matchWholeTemplates = /:([\w-]*):/g
const maskForWholeTemplates = '😸$1😸'
return query.replace(matchWholeTemplates, maskForWholeTemplates)
@ -215,7 +215,7 @@ export const applyMasks = (query) => {
export const insertTempVar = (query, tempVar) => {
return query.replace(MATCH_INCOMPLETE_TEMPLATES, tempVar)
}
export const unMask = (query) => {
export const unMask = query => {
return query.replace(/😸/g, ':')
}
export const TEMPLATE_RANGE: TimeRange = {

View File

@ -35,7 +35,7 @@ const getMetaQueryPrefix = (metaQuery: string): string | null => {
const firstThreeWords = words.slice(0, 3).join(' ')
return VALID_META_QUERY_PREFIXES.find(
(q) => q === firstTwoWords || q === firstThreeWords
q => q === firstTwoWords || q === firstThreeWords
)
}
@ -58,14 +58,14 @@ const PARSERS = {
}
const EXTRACTORS = {
'SHOW DATABASES': (parsed) => parsed.databases,
'SHOW FIELD KEYS': (parsed) => {
'SHOW DATABASES': parsed => parsed.databases,
'SHOW FIELD KEYS': parsed => {
const {fieldSets} = parsed
const fieldSetsValues = Object.values(fieldSets) as string[]
return fieldSetsValues.reduce((acc, current) => [...acc, ...current], [])
},
'SHOW MEASUREMENTS': (parsed) => {
'SHOW MEASUREMENTS': parsed => {
const {measurementSets} = parsed
return measurementSets.reduce(
@ -73,12 +73,12 @@ const EXTRACTORS = {
[]
)
},
'SHOW TAG KEYS': (parsed) => parsed.tagKeys,
'SHOW TAG VALUES': (parsed) => {
'SHOW TAG KEYS': parsed => parsed.tagKeys,
'SHOW TAG VALUES': parsed => {
const {tags} = parsed
const tagsValues = Object.values(tags) as string[]
return tagsValues.reduce((acc, current) => [...acc, ...current], [])
},
'SHOW SERIES': (parsed) => parsed.series,
'SHOW SERIES': parsed => parsed.series,
}

View File

@ -109,7 +109,7 @@ export function graphFromTemplates(templates: Template[]): TemplateGraph {
for (const template of templates) {
const childNames = getDependencyNames(template)
const nodeIsChild = (n) => childNames.includes(n.initialTemplate.tempVar)
const nodeIsChild = n => childNames.includes(n.initialTemplate.tempVar)
const children = nodes.filter(nodeIsChild)
nodesById[template.id].children.push(...children)
@ -154,7 +154,7 @@ function topologicalSortHelper(
}
function findLeaves(graph: TemplateGraph): TemplateNode[] {
return graph.filter((node) => !node.children.length)
return graph.filter(node => !node.children.length)
}
function isResolved(node: TemplateNode): boolean {
@ -248,14 +248,12 @@ export async function hydrateTemplates(
async function resolve(node: TemplateNode) {
const resolvedTemplates = graph
.filter(isResolved)
.map((t) => t.hydratedTemplate)
.map(t => t.hydratedTemplate)
node.status = RemoteDataState.Loading
const {initialTemplate} = node
const templateSource = sources.find(
(s) => s.id === initialTemplate.sourceID
)
const templateSource = sources.find(s => s.id === initialTemplate.sourceID)
const proxyUrl = templateSource
? templateSource.links.proxy
@ -270,7 +268,7 @@ export async function hydrateTemplates(
node.status = RemoteDataState.Done
const parents = node.parents
.filter((p) => p.children.every(isResolved))
.filter(p => p.children.every(isResolved))
.map(resolve)
return Promise.all(parents)
@ -278,5 +276,5 @@ export async function hydrateTemplates(
await Promise.all(findLeaves(graph).map(resolve))
return graph.map((t) => t.hydratedTemplate)
return graph.map(t => t.hydratedTemplate)
}

View File

@ -9,14 +9,14 @@ import {
TemplateValueType,
} from 'src/types'
export const trimAndRemoveQuotes = (elt) => {
export const trimAndRemoveQuotes = elt => {
const trimmed = elt.trim()
const dequoted = trimmed.replace(/(^")|("$)/g, '')
return dequoted
}
export const formatTempVar = (name) =>
export const formatTempVar = name =>
`:${name.replace(/:/g, '').replace(/\s/g, '')}:`
export const resolveValues = (
@ -73,7 +73,7 @@ const newTemplateValueQuery = (
localSelectedValue = selectedValue
}
return newValues.map((value) => {
return newValues.map(value => {
return {
type,
value,
@ -91,27 +91,27 @@ const newTemplateValueConstant = (
return []
}
let selectedValue = template.values.find((v) => v.selected)
let selectedValue = template.values.find(v => v.selected)
if (!selectedValue) {
selectedValue = template.values[0]
}
let localSelectedValue = template.values.find((v) => {
let localSelectedValue = template.values.find(v => {
return template.type === TemplateType.Map
? v.key === hopefullySelectedValue
: v.value === hopefullySelectedValue
})
if (!localSelectedValue) {
localSelectedValue = template.values.find((v) => v.localSelected)
localSelectedValue = template.values.find(v => v.localSelected)
}
if (!localSelectedValue) {
localSelectedValue = selectedValue
}
return template.values.map((v) => ({
return template.values.map(v => ({
...v,
selected: v.value === selectedValue.value,
localSelected: v.value === localSelectedValue.value,
@ -146,7 +146,7 @@ const newTemplateValueText = (
}
export const getSelectedValue = (template: Template): string | null => {
const selected = template.values.find((v) => v.selected)
const selected = template.values.find(v => v.selected)
if (selected) {
return selected.value
@ -156,7 +156,7 @@ export const getSelectedValue = (template: Template): string | null => {
}
export const getLocalSelectedValue = (template: Template): string | null => {
const selected = template.values.find((v) => v.localSelected)
const selected = template.values.find(v => v.localSelected)
if (selected) {
return selected.value
@ -209,4 +209,4 @@ export const csvToMap = (csv: string): MapResult => {
}
export const mapToCSV = (values: TemplateValue[]): string =>
values.map((v) => `${v.key},"${v.value}"`).join('\n')
values.map(v => `${v.key},"${v.value}"`).join('\n')

View File

@ -27,7 +27,7 @@ export const replaceInterval = (query: string, durationMs: number) => {
const sortTemplates = (templates: Template[]): Template[] => {
const graph = graphFromTemplates(templates)
return topologicalSort(graph).map((t) => t.initialTemplate)
return topologicalSort(graph).map(t => t.initialTemplate)
}
const templateReplace = (query: string, templates: Template[]) => {
@ -49,10 +49,10 @@ const renderTemplate = (query: string, template: Template): string => {
}
const localSelectedTemplateValue: TemplateValue = template.values.find(
(v) => v.localSelected
v => v.localSelected
)
const selectedTemplateValue: TemplateValue = template.values.find(
(v) => v.selected
v => v.selected
)
const templateValue = localSelectedTemplateValue || selectedTemplateValue

View File

@ -10,7 +10,7 @@ export class AutoRefresher {
}
public unsubscribe(fn: func) {
this.subscribers = this.subscribers.filter((f) => f !== fn)
this.subscribers = this.subscribers.filter(f => f !== fn)
}
public poll(refreshMs: number) {
@ -35,7 +35,7 @@ export class AutoRefresher {
}
private refresh = () => {
this.subscribers.forEach((fn) => fn())
this.subscribers.forEach(fn => fn())
}
}

View File

@ -25,8 +25,8 @@ const buildQueries = (queryConfigs: QueryConfig[], tR: TimeRange): Query[] => {
if (shifts && shifts.length && isParsable) {
const shiftedQueries: string[] = shifts
.filter((s) => s.unit)
.map((s) => buildQuery(TYPE_SHIFTED, timeRange, query, s))
.filter(s => s.unit)
.map(s => buildQuery(TYPE_SHIFTED, timeRange, query, s))
return {
text: `${text};${shiftedQueries.join(';')}`,
@ -39,7 +39,7 @@ const buildQueries = (queryConfigs: QueryConfig[], tR: TimeRange): Query[] => {
})
const queries: Query[] = statements
.filter((s) => s.text !== null)
.filter(s => s.text !== null)
.map(({queryConfig, text, id}) => {
return {
text,

View File

@ -15,9 +15,7 @@ const buildCannedDashboardQuery = (
{lower, upper}: TimeRange,
host: string
): string => {
const {defaultGroupBy} = timeRanges.find(
(range) => range.lower === lower
) || {
const {defaultGroupBy} = timeRanges.find(range => range.lower === lower) || {
defaultGroupBy: '5m',
}
@ -40,7 +38,7 @@ const buildCannedDashboardQuery = (
}
if (groupbys) {
if (groupbys.find((g) => g.includes('time'))) {
if (groupbys.find(g => g.includes('time'))) {
text += ` group by ${groupbys.join(',')}`
} else if (groupbys.length > 0) {
text += ` group by time(${defaultGroupBy}),${groupbys.join(',')}`
@ -89,7 +87,7 @@ export const buildQueriesForLayouts = (
timeRange: TimeRange,
host: string
): CellQuery[] => {
return cell.queries.map((query) => {
return cell.queries.map(query => {
let queryText: string
// Canned dashboards use an different a schema different from queryConfig.
if (query.queryConfig) {
@ -109,8 +107,8 @@ export const buildQueriesForLayouts = (
if (shifts && shifts.length && isParsable) {
const shiftedQueries: string[] = shifts
.filter((s) => s.unit)
.map((s) => buildQuery(TYPE_SHIFTED, timeRange, query.queryConfig, s))
.filter(s => s.unit)
.map(s => buildQuery(TYPE_SHIFTED, timeRange, query.queryConfig, s))
queryText = `${queryText};${shiftedQueries.join(';')}`
}

View File

@ -66,7 +66,7 @@ const flattenGroupBySeries = (
const accumulatedValues = fastReduce<TimeSeriesSeries, TimeSeriesValue[][]>(
seriesArray,
(acc, s) => {
const tagsToAdd: string[] = tagsKeys.map((tk) => s.tags[tk])
const tagsToAdd: string[] = tagsKeys.map(tk => s.tags[tk])
const values = s.values
const newValues = values.map(([first, ...rest]) => [
first,
@ -111,7 +111,7 @@ const constructResults = (
)
const successfulResults = results.filter(
(r) => 'series' in r && !('error' in r)
r => 'series' in r && !('error' in r)
) as TimeSeriesSuccessfulResult[]
const tagsFromResults: {[x: string]: string} = _.get(
@ -131,7 +131,7 @@ const constructResults = (
const noGroupBySeries = fastMap<TimeSeriesSuccessfulResult, Result>(
successfulResults,
(r) => ({
r => ({
...r,
responseIndex: index,
})
@ -193,13 +193,13 @@ const constructCells = (
},
ind
) => {
if (columns.find((c) => c === 'time')) {
if (columns.find(c => c === 'time')) {
let unsortedLabels: Label[]
if (isGroupBy) {
const labelsFromTags = fastMap<string, Label>(
_.keys(tags),
(field) => ({
field => ({
label: `${field}`,
responseIndex,
seriesIndex,
@ -207,7 +207,7 @@ const constructCells = (
)
const labelsFromColumns = fastMap<string, Label>(
columns.slice(1),
(field) => ({
field => ({
label: `${measurement}.${field}`,
responseIndex,
seriesIndex,
@ -220,22 +220,19 @@ const constructCells = (
} else {
const tagSet = fastMap<string, string>(
_.keys(tags),
(tag) => `[${tag}=${tags[tag]}]`
tag => `[${tag}=${tags[tag]}]`
)
.sort()
.join('')
unsortedLabels = fastMap<string, Label>(
columns.slice(1),
(field) => ({
label: `${measurement}.${field}${tagSet}`,
responseIndex,
seriesIndex,
})
)
unsortedLabels = fastMap<string, Label>(columns.slice(1), field => ({
label: `${measurement}.${field}${tagSet}`,
responseIndex,
seriesIndex,
}))
seriesLabels[ind] = unsortedLabels
labels = _.concat(labels, unsortedLabels)
fastForEach(values, (vals) => {
fastForEach(values, vals => {
const [time, ...rowValues] = vals
fastForEach(rowValues, (value, i) => {
cells.label[cellIndex] = unsortedLabels[i].label
@ -252,7 +249,7 @@ const constructCells = (
isMetaQuery = true
if (serieses.length === 1) {
labels = columns.map((c) => ({
labels = columns.map(c => ({
label: c,
responseIndex,
seriesIndex,
@ -260,7 +257,7 @@ const constructCells = (
metaQuerySeries = [columns, ...values]
} else {
labels = columns.map((c) => ({
labels = columns.map(c => ({
label: c,
responseIndex,
seriesIndex,
@ -273,7 +270,7 @@ const constructCells = (
const [, ...vals] = metaQuerySeries
const allValuesForMeasurement = values.map((val) => {
const allValuesForMeasurement = values.map(val => {
return [measurement, ...val]
})
@ -408,7 +405,7 @@ const constructTimeSeries = (
}
// change all undefined values to null, these values were not set
timeSeries.forEach((x) => {
timeSeries.forEach(x => {
for (let i = 0; i < x.values.length; i++) {
if (x.values[i] === undefined) {
x.values[i] = null

View File

@ -98,7 +98,7 @@ function buildFields(
return []
}
return fieldFuncs.map((f) => {
return fieldFuncs.map(f => {
switch (f.type) {
case 'field': {
const quoted = f.value === '*' ? '*' : `"${f.value}"`
@ -156,18 +156,18 @@ export function buildWhereClause({
// otherwise
// join the tag key with an AND (i.e. cpu!=cpu1 AND cpu!=cpu2)
// we do this because cpu!=cpu1 AND cpu!=cpu2 excludes no data
const tagClauses = _.keys(tags).map((k) => {
const tagClauses = _.keys(tags).map(k => {
const operator = areTagsAccepted ? '=' : '!='
const cond = areTagsAccepted ? ' OR ' : ' AND '
if (tags[k].length > 1) {
const joinedOnOr = tags[k]
.map((v) => `"${k}"${operator}'${v.replace(/'/g, "\\'")}'`)
.map(v => `"${k}"${operator}'${v.replace(/'/g, "\\'")}'`)
.join(cond)
return `(${joinedOnOr})`
}
return `"${k}"${operator}'${tags[k].map((v) => v.replace(/'/g, "\\'"))}'`
return `"${k}"${operator}'${tags[k].map(v => v.replace(/'/g, "\\'"))}'`
})
const subClauses = timeClauses.concat(tagClauses)
@ -197,7 +197,7 @@ function buildGroupByTags(groupBy: GroupBy): string {
return ''
}
const tags = groupBy.tags.map((t) => `"${t}"`).join(', ')
const tags = groupBy.tags.map(t => `"${t}"`).join(', ')
if (groupBy.time) {
return `, ${tags}`

View File

@ -88,7 +88,7 @@ export const toggleField = (
): QueryConfig => {
const {fields = [], groupBy} = query
const isSelected = hasField(value, fields)
const newFuncs = fields.filter((f) => f.type === 'func')
const newFuncs = fields.filter(f => f.type === 'func')
if (isSelected) {
// if list is all fields, remove that field
@ -165,7 +165,7 @@ export const applyFuncsToField = (
if (f.type === 'field') {
return [
...acc,
funcs.map((func) => {
funcs.map(func => {
const {value, type} = func
const args = [{value: f.value, type: 'field'}]
const alias = func.alias ? func.alias : `${func.value}_${f.value}`
@ -180,12 +180,12 @@ export const applyFuncsToField = (
]
}
const fieldToChange = f.args.find((a) => a.value === field.value)
const fieldToChange = f.args.find(a => a.value === field.value)
// Apply new funcs to field
if (fieldToChange) {
const newFuncs = funcs.reduce((acc2, func) => {
const funcsToChange = getFuncsByFieldName(fieldToChange.value, acc)
const dup = funcsToChange.find((a) => a.value === func.value)
const dup = funcsToChange.find(a => a.value === func.value)
if (dup) {
return acc2

View File

@ -1,4 +1,4 @@
export const clipPathUrl = (elementId) => {
export const clipPathUrl = elementId => {
// Other SVG elements are often referenced in SVG attributes like `clip-path`
// and `mask` using a url, e.g.
//

View File

@ -25,9 +25,7 @@ export const timeSeriesToDygraph = async (
timeSeries,
([time, ...values]) => {
if (unsupportedValue === undefined) {
unsupportedValue = values.find(
(x) => x !== null && typeof x !== 'number'
)
unsupportedValue = values.find(x => x !== null && typeof x !== 'number')
}
return [new Date(time), ...values]
}

View File

@ -93,7 +93,7 @@ class JobManager {
return this.publishDBJob('VALIDATEDYGRAPHDATA', ts)
}
private handleMessage = async (msg) => {
private handleMessage = async msg => {
const {data} = msg
const deferred = this.jobs[data.origin]
if (deferred) {
@ -117,7 +117,7 @@ class JobManager {
}
}
private handleError = (err) => {
private handleError = err => {
console.error(err)
}

View File

@ -1,6 +1,6 @@
import axios from 'axios'
const proxy = async (msg) => {
const proxy = async msg => {
const {
payload: {url, query, rp, db, uuid},
} = msg

View File

@ -1,7 +1,7 @@
import {fetchData} from 'src/worker/utils'
import {transformTableData} from 'src/dashboards/utils/tableGraph'
const tableTransform = async (msg) => {
const tableTransform = async msg => {
const dbResult = await fetchData(msg)
const {

View File

@ -55,7 +55,7 @@ export const timeSeriesToDygraphWork = (
return {labels, timeSeries, dygraphSeries}
}
const timeSeriesToDygraph = async (msg) => {
const timeSeriesToDygraph = async msg => {
const {raw} = await fetchData(msg)
return timeSeriesToDygraphWork(raw)

View File

@ -7,7 +7,7 @@ import {Message} from 'src/worker/types'
const validateDygraphData = async (msg: Message): Promise<boolean> => {
const ts: DygraphValue[][] = await fetchData(msg)
return _.every(ts, (r) =>
return _.every(ts, r =>
_.every(
r,
(v: any, i: number) =>