Applying a queryRewrite filter only if a certain dimention exists
Problem
I would like to use the queryRewrite method to filter by the values of a certain dimension, but only if this dimension exists on a certain cube.
I wrote a small js function that I call within the queryRewrite method that validates if there is a dimension dimension in a cube with name cubeName. This function will then go through all my models and check if such cube with the specific dimension exists.
This seems a bit hacky though, so I was wondering if there was a better way of achieving this (by this I mean, if I specify a filter to a dimension that does not exist on the cube, this filter is just ignored instead of raising an error).
// Checks if a certain cube contains a given dimension. Returns a boolean
// folder is the folder where all the models are
function checkIfDimensionExists(cubeName, dimension, folder) {
for (const file of fs.readdirSync(folder).filter(f => f.endsWith(".yml"))) {
// Load yaml file
const yamlCubes = yaml.load(fs.readFileSync(path.join(folder, file), 'utf8'))['cubes']
// Check if the dimension exists
for (const cube of yamlCubes) {
if ((cube.name === cubeName) && cube.dimensions.filter(d => d.name === dimension).length > 0) {
return true
}
}
}
return false
}
Just as an example of what my queryRewrite method might look like:
queryRewrite: (query, { securityContext }) => {
const dimension = "tenant"
// TODO: This needs to be improved, as it only works on queries like `query={"measures":["cubeName.count"]}`
const cube = query['measures'][0].split('.')[0]
// Only applies a query rewrite if a dimension exists on the cube
if (checkIfDimensionExists(cube, dimension, "/cube/conf/model")) {
query.filters.push({
member: cube + '.' + dimension,
operator: "equals",
values: [securityContext.tenant],
});
} else {
console.log(`Dimension: ${dimension} does not exist on Cube: ${cube}`)
}
console.log(`Final Query: ${query}`)
return query;
},