Files
supabase/apps/studio/hooks/useChartData.ts
T
f65884f341 Reports consolidation 1: Edge Functions (#38129)
* wip

* add formatTimestamp for reports

* add tests for formatTimestamp

* fix type err

* rm old chart logic

* do not retry replication sources

* update report config schema

* use report config

* fix charts, simplify config

* sync charts

* rm comment

* usefilltimeseries

* move chart upsell to its own component

* cleanup v2 chart component

* fix chartheader function format bug

* make attributes dynamic

* move types to its own file

* update reportv2chart types

* update reportv2 chart type

* use new edgefn report

* rm mock

* rm old code

* fix type err

* fix type err

* rename hook

* return sql in dataprovider

* add button to open in log explorer in chart header

* fix type

* fix chart type toggle

* fix type error

* export data transformation for testing

* add tests for data transformation

* rm dupped code

* add report settings to edge fn report

* rm mocked data

* rename

* fix type err

* Apply suggestion from @joshenlim

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>

* rm unnecessary div

* rm unnecessary props from report upsell

* cleaner query keys

* move loadin/error/empty states to inside panel content to prevent layout shift

* use card instead of panel

* use buttontooltip in chartheader

* use buttontooltips in buttons with tooltips

* rm export default

* rm export defualt

* rm i from key

* fix status code transformation

* fix filltimeseries

* add tests for filltimeseries

* fix data transform

* pass xaxis key to chart

* refactor hover state to use timestamp not index

* fix tests

* fix areachart

* fix barchart

* fix chartheader

* fix composedchart

* fix stacked

* fix type missing xaxiskey

* type fix

* Revert "refactor hover state to use timestamp not index"

This reverts commit cfd7886460.

* undo charthover changes, fix data aggregation

* Revert "fix tests"

This reverts commit e5200a2035.

* move transforms to testable functions, add tests

* nit refactors and clean up

* feat: add aws nimbus cloud provider (#38312)

* feat: add aws nimbus cloud provider

* Fix return type of useCustomContent hook

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>

* add utc plugin to dayjs

* move plugins to vitest setup

* rm customparser plugin

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
Co-authored-by: Alaister Young <alaister@users.noreply.github.com>
2025-09-01 11:10:30 +02:00

124 lines
3.7 KiB
TypeScript

/**
* useChartData
*
* A hook for fetching and processing data for a chart.
* This hook is responsible for all the data fetching, combining, and state management logic
* that was previously inside ComposedChartHandler.
*
* It takes all necessary parameters like project reference, date range, and attributes,
* and returns the final chart data, loading state, and derived attributes.
*/
import { useMemo } from 'react'
import { useRouter } from 'next/router'
import type { AnalyticsInterval, DataPoint } from 'data/analytics/constants'
import { useAuthLogsReport } from 'data/reports/auth-report-query'
import type { ChartData } from 'components/ui/Charts/Charts.types'
import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'
export const useChartData = ({
attributes,
startDate,
endDate,
interval,
data,
highlightedValue,
functionIds,
enabled = true,
}: {
attributes: MultiAttribute[]
startDate: string
endDate: string
interval: string
data?: ChartData
highlightedValue?: string | number
functionIds?: string[]
enabled?: boolean
}) => {
const router = useRouter()
const { ref } = router.query
const logsAttributes = attributes.filter((attr) => attr.provider === 'logs')
const isEdgeFunctionRoute = router.asPath.includes('/reports/edge-functions')
const {
data: authData,
attributes: authChartAttributes,
isLoading: isAuthLoading,
} = useAuthLogsReport({
projectRef: ref as string,
attributes: logsAttributes,
startDate,
endDate,
interval: interval as AnalyticsInterval,
enabled: enabled && logsAttributes.length > 0 && !isEdgeFunctionRoute,
})
const logsData = authData
const logsChartAttributes = authChartAttributes
const isLogsLoading = isAuthLoading
const combinedData = useMemo(() => {
if (data) return data
// Get all unique timestamps from all datasets
const timestamps = new Set<string>()
if (logsData) {
logsData.forEach((point: any) => {
if (point?.period_start) {
timestamps.add(point.period_start)
}
})
}
// Combine data points for each timestamp
const combined = Array.from(timestamps)
.sort()
.map((timestamp) => {
const point: any = { period_start: timestamp }
const logPoint = logsData?.find((p: any) => p.period_start === timestamp) || {}
Object.assign(point, logPoint)
return point as DataPoint
})
return combined as DataPoint[]
}, [data, attributes, isLogsLoading, logsData, logsAttributes])
const loading = logsAttributes.length > 0 && isLogsLoading
// Calculate highlighted value based on the first attribute's data
const _highlightedValue = useMemo(() => {
if (highlightedValue !== undefined) return highlightedValue
const firstAttr = attributes[0]
const firstData = logsChartAttributes.find((p: any) => p.attribute === firstAttr.attribute)
if (!firstData) return undefined
const shouldHighlightMaxValue =
firstAttr.provider === 'daily-stats' &&
!firstAttr.attribute.includes('ingress') &&
!firstAttr.attribute.includes('egress') &&
'maximum' in firstData
const shouldHighlightTotalGroupedValue = 'totalGrouped' in firstData
return shouldHighlightMaxValue
? firstData.maximum
: firstAttr.provider === 'daily-stats'
? firstData.total
: shouldHighlightTotalGroupedValue
? firstData.totalGrouped?.[firstAttr.attribute as keyof typeof firstData.totalGrouped]
: (firstData.data?.[firstData.data?.length - 1] as any)?.[firstAttr.attribute]
}, [highlightedValue, attributes])
return {
data: combinedData,
isLoading: loading,
highlightedValue: _highlightedValue,
}
}