@opengis/bi
Version:
BI data visualization module
66 lines (55 loc) • 2.65 kB
JavaScript
function normalizeData(data, query = {}, columnTypes = []) {
const skip = [];
['x', 'groupby', 'granularity'].forEach((el) => {
// console.log(el, query[el], columnTypes.find(col => col.name == query[el]))
if (!columnTypes.find((col) => col.name == query[el])) {
if (query[el] && query[el] !== 'null') {
if (el === 'granularity' && !['week', 'month', 'quarter', 'year'].includes(query[el])) {
skip.push(`invalid granularity option: ${query[el]}`);
} else if (el !== 'granularity') { skip.push(`column not found: ${query[el]}`); }
}
if (!(el === 'granularity' || (el === 'groupby' && query[el] === 'null'))) delete query[el];
}
});
if (
!columnTypes.find(
(col) => col.type === 'numeric' && col.name == query.metric
)
) {
delete query.metric;
}
const xName = query.x || (Array.isArray(data.x) ? data.x[0] : data.x);
const xType = columnTypes.find((el) => el.name == xName)?.type;
const granularity =
xType === 'date' || xType?.includes('timestamp')
? query.granularity || data.granularity || 'year'
: null;
const x =
(granularity
? `date_trunc('${granularity}',${xName})::date::text`
: null) || xName;
const metrics = Array.isArray(data.metrics || data.metric) ? (data.metrics || data.metric) : [data.metrics || data.metric];
const metric =
(query.metric ? `sum(${query.metric})` : null) ||
(metrics.length
? (metrics
?.filter((el) => el && columnTypes.find((col) => col.name == (el?.name || el)))
?.map((el) => el.fx || `${el.operator || 'sum'}(${el.name || el})`)?.join(',') || 'count(*)')
: 'count(*)');
const yName = metrics?.[0]?.name || metrics?.[0];
const yType = columnTypes.find((el) => el.name == yName)?.type;
const { cls, groupbyCls, table, filterCustom } = data;
const groupby = (query.groupby || data.groupby) === 'null' ? null : (query.groupby || data.groupby);
// const orderby = query.orderby || data.orderby || 'count(*)';
const custom = query?.filterCustom
?.split(',')
?.map((el) => filterCustom?.find((item) => item?.name === el)?.sql)
?.filter((el) => el)
?.join(' and ');
const where = `${data.query || '1=1'} and ${custom || 'true'}`;
const tableSQL = data.tableSQL?.length
? `(select * from ${data?.table} t ${data.tableSQL || ''} where ${where})q`
: undefined;
return { x, cls, groupbyCls, metric, table, where, tableSQL, groupby, xName, xType, yName, yType, error: skip.length ? skip.join(',') : undefined };
}
export default normalizeData;