-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathuse-chart-data.ts
More file actions
184 lines (159 loc) · 4.92 KB
/
use-chart-data.ts
File metadata and controls
184 lines (159 loc) · 4.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import type { Table } from "apache-arrow";
import { useMemo } from "react";
import type { ChartData, DataFormat } from "../charts/types";
import { useAnalyticsQuery } from "./use-analytics-query";
/** Threshold for auto-selecting Arrow format (row count hint) */
const ARROW_THRESHOLD = 500;
// ============================================================================
// Hook Options & Result Types
// ============================================================================
export interface UseChartDataOptions {
/** Analytics query key */
queryKey: string;
/** Query parameters */
parameters?: Record<string, unknown>;
/**
* Data format preference
* - "json": Force JSON format
* - "arrow": Force Arrow format
* - "auto": Auto-select based on heuristics
* @default "auto"
*/
format?: DataFormat;
/** Transform data after fetching */
transformer?: <T>(data: T) => T;
}
export interface UseChartDataResult {
/** The fetched data (Arrow Table or JSON array) */
data: ChartData | null;
/** Whether the data is in Arrow format */
isArrow: boolean;
/** Loading state */
loading: boolean;
/** Error message if any */
error: string | null;
/** Whether the data is empty */
isEmpty: boolean;
}
// ============================================================================
// Format Resolution
// ============================================================================
/**
* Resolves the data format based on hints and preferences
*/
function resolveFormat(
format: DataFormat,
parameters?: Record<string, unknown>,
): "JSON" | "ARROW" | "ARROW_STREAM" {
// Explicit format selection
if (format === "json") return "JSON";
if (format === "arrow") return "ARROW";
if (format === "arrow_stream") return "ARROW_STREAM";
// Auto-selection heuristics
if (format === "auto") {
// Check for explicit hint in parameters
if (parameters?._preferArrow === true) return "ARROW";
if (parameters?._preferJson === true) return "JSON";
// Check limit parameter as data size hint
const limit = parameters?.limit;
if (typeof limit === "number" && limit > ARROW_THRESHOLD) {
return "ARROW";
}
// Check for date range queries (often large)
if (parameters?.startDate && parameters?.endDate) {
return "ARROW";
}
return "ARROW_STREAM";
}
return "ARROW_STREAM";
}
// ============================================================================
// Main Hook
// ============================================================================
/**
* Hook for fetching chart data in either JSON or Arrow format.
* Automatically selects the best format based on query hints.
*
* @example
* ```tsx
* // Auto-select format
* const { data, isArrow, loading } = useChartData({
* queryKey: "spend_data",
* parameters: { limit: 1000 }
* });
*
* // Force Arrow format
* const { data } = useChartData({
* queryKey: "big_query",
* format: "arrow"
* });
* ```
*/
export function useChartData(options: UseChartDataOptions): UseChartDataResult {
const { queryKey, parameters, format = "auto", transformer } = options;
// Resolve the format to use
const resolvedFormat = useMemo(
() => resolveFormat(format, parameters),
[format, parameters],
);
const isArrowFormat = resolvedFormat === "ARROW";
// Fetch data using the analytics query hook
const {
data: rawData,
loading,
error,
} = useAnalyticsQuery(queryKey, parameters, {
autoStart: true,
format: resolvedFormat,
});
// Process and transform data
const processedData = useMemo(() => {
if (!rawData) return null;
// Apply transformer if provided
if (transformer) {
try {
return transformer(rawData);
} catch (err) {
console.error("[useChartData] Transformer error:", err);
return rawData;
}
}
return rawData;
}, [rawData, transformer]);
// Determine if data is empty
const isEmpty = useMemo(() => {
if (!processedData) return true;
// Arrow Table - check using duck typing
if (
typeof processedData === "object" &&
"numRows" in processedData &&
typeof (processedData as Table).numRows === "number"
) {
return (processedData as Table).numRows === 0;
}
// JSON Array
if (Array.isArray(processedData)) {
return processedData.length === 0;
}
return true;
}, [processedData]);
// Detect actual data type (may differ from requested if server doesn't support format)
const isArrow = useMemo(() => {
if (!processedData) return isArrowFormat;
// Duck type check for Arrow Table
return (
typeof processedData === "object" &&
processedData !== null &&
"schema" in processedData &&
"numRows" in processedData &&
typeof (processedData as Table).getChild === "function"
);
}, [processedData, isArrowFormat]);
return {
data: processedData as ChartData | null,
isArrow,
loading,
error,
isEmpty,
};
}