How to check user input is a valid column before appending condition?

Does anyone knows the proper way to do so?
if (columnFilters.length > 0) {
const columnWhereClause: (SQL | undefined)[] = columnFilters.map(
(filter) => {
const columns = getTableColumns(tasks);

if (filter.column in columns) {
// getting error on columns[filter.column]: type 'string' can't be used to index type
return ilike(columns[filter.column], `%${filter.keyword}%`);
}
},
);
whereClause.push(and(...columnWhereClause));
}
if (columnFilters.length > 0) {
const columnWhereClause: (SQL | undefined)[] = columnFilters.map(
(filter) => {
const columns = getTableColumns(tasks);

if (filter.column in columns) {
// getting error on columns[filter.column]: type 'string' can't be used to index type
return ilike(columns[filter.column], `%${filter.keyword}%`);
}
},
);
whereClause.push(and(...columnWhereClause));
}
3 Replies
Sillvva
Sillvva6mo ago
Can you show the how you defined the columnFilters variable?
Sillvva
Sillvva6mo ago
Basically, rather than string, the filter.column property should be of type keyof typeof tasks["_"]["columns"]. For example:
No description
ArChak
ArChakOP6mo ago
suer, here is the definition, seems I have to make this generic to fit other table as well, thank you
export class SearchColumnFilter {
@ApiProperty()
@IsString()
@IsNotEmpty()
column: string;

@ApiProperty()
@IsString()
@IsNotEmpty()
keyword: string;
}
export class SearchColumnFilter {
@ApiProperty()
@IsString()
@IsNotEmpty()
column: string;

@ApiProperty()
@IsString()
@IsNotEmpty()
keyword: string;
}
Want results from more Discord servers?
Add your server