forked from cube-js/cube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toChartjsData.js
76 lines (67 loc) · 1.82 KB
/
toChartjsData.js
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
const COLORS_SERIES = ['#FF6492', '#141446', '#7A77FF'];
const toChartjsOptions = (chartType, resultSet) => {
// TODO: Check for supported charts
let options = {};
if ((resultSet.query().timeDimensions || []).find(td => !!td.granularity)) {
options.scales = { xAxes: [{ type: `time`, time: { unit: 'month' }}] };
}
return options;
}
const toChartjsData = (chartType, resultSet) => {
if (chartType === 'pie') {
return {
labels: resultSet.categories().map(c => c.category),
datasets: resultSet.series().map(s => (
{
label: s.title,
data: s.series.map(r => r.value),
backgroundColor: COLORS_SERIES,
hoverBackgroundColor: COLORS_SERIES,
}
))
}
}
const formatter = (category) => {
// TODO: Use Moment/Luxon or rely on the info
// from API
if (Date.parse(category)) {
return new Date(category);
} else {
return category
}
}
if (chartType === 'line') {
return {
labels: resultSet.categories().map(c => formatter(c.category)),
datasets: resultSet.series().map((s, index) => (
{
label: s.title,
data: s.series.map(r => r.value),
borderColor: COLORS_SERIES[index],
fill: false
}
)),
}
}
if (chartType === 'bar') {
return {
labels: resultSet.categories().map(c => formatter(c.category)),
datasets: resultSet.series().map((s, index) => (
{
label: s.title,
data: s.series.map(r => r.value),
backgroundColor: COLORS_SERIES[index],
fill: false
}
)),
}
}
}
const chartjsConfig = (chartType, resultSet) => (
{
data: toChartjsData(chartType, resultSet),
options: toChartjsOptions(chartType, resultSet),
type: chartType
}
)
export default chartjsConfig;