Hi All,
to make more flexible the creation of standard views, I'm trying to define them using javascript, but I can't assign a description to columns. This is an example code:
const col = "COL1: \"test col\"";
publish("testview",{
type: "view",
columns: {col}
}).query(ctx => "SELECT 1 AS COL1")
The view has been created but no description is available for COL1
This work:
publish("testview",{
type: "view",
columns: {COL1: "test col"}
}).query(ctx => "SELECT 1 AS COL1")
but I've to put this sentence in a for loop to create lots of views based on different queries.
Can anyone help me?
Thanks
Solved! Go to Solution.
You're correct in avoiding the use of eval
for dynamically constructing code due to its potential security and performance implications. Instead, a cleaner and safer approach is to create views with variable numbers of columns and distinct queries using JavaScript object manipulation. Here’s how you can achieve this:
Example:
const viewDefinitions = [
{
name: "view1",
columns: [
{ name: "COL1", description: "Description for COL1" },
{ name: "COL2", description: "Description for COL2" }
],
query: () => `SELECT 1 AS COL1, 2 AS COL2` // Custom query for view1
},
{
name: "view2",
columns: [
{ name: "COL3", description: "Description for COL3" },
{ name: "COL4", description: "Description for COL4" },
{ name: "COL5", description: "Description for COL5" }
],
query: () => `SELECT 3 AS COL3, 4 AS COL4, 5 AS COL5` // Custom query for view2
}
// Additional view definitions can be added here as needed
];
viewDefinitions.forEach(viewDef => {
const columnDefinitions = viewDef.columns.reduce((acc, col) => {
acc[col.name] = col.description; // Dynamically build column definitions
return acc;
}, {});
publish(viewDef.name, { type: "view", columns: columnDefinitions })
.query(viewDef.query); // Apply the custom query for this view
});
Explanation:
viewDefinitions
Array: This contains objects, each defining a view's configuration, including the name, columns, and the query..reduce()
on the columns
array to transform it into the required object structure for the columns
property in the publish
function.publish
Call: Invokes the publish
function with the dynamically constructed columns object, the view's name, and specifying it as a "view".query()
Call: Chains this method to publish
to assign the custom SQL query for the view.Key Improvements:
eval
by utilizing safe JavaScript practices.viewDefinitions
array.