Dynamic query columns projection

Hey, i'm trying to do a dynamic selection of columns in my queries, having before hand an array of the wanted columns from the table, its postgres btw
const projection = fieldsProjection(info);
console.log(projection)
const query = db.select().from(drivers);
const projection = fieldsProjection(info);
console.log(projection)
const query = db.select().from(drivers);
the projection array looks for example like this
[ 'id', 'username', 'password', 'email' ]
[ 'id', 'username', 'password', 'email' ]
if someone had to do something similar before, please insight me, tried some of the solutions from github issues but things were messy and didn't work, thought maybe someone found something better in this case
1 Reply
Ayoub
AyoubOP9mo ago
SOLUTION: did this
const createProjectionObject = (columns: string[]) => {
const projection = {};
columns.forEach((column) => {
projection[column] = sql`${sql.identifier(column)}`;
});
return projection;
};
const projectionObject = createProjectionObject(fieldsProjection(info)); // it takes GraphQL info object and gets the selected fields
const queryResult = await db.select(projectionObject).from(drivers).limit(limit).offset(offset)
const createProjectionObject = (columns: string[]) => {
const projection = {};
columns.forEach((column) => {
projection[column] = sql`${sql.identifier(column)}`;
});
return projection;
};
const projectionObject = createProjectionObject(fieldsProjection(info)); // it takes GraphQL info object and gets the selected fields
const queryResult = await db.select(projectionObject).from(drivers).limit(limit).offset(offset)
Want results from more Discord servers?
Add your server