Skip to content

Instantly share code, notes, and snippets.

@fiote
Created June 30, 2022 23:45
Show Gist options
  • Save fiote/3433b1ad5c7f12a55534ce989e88552f to your computer and use it in GitHub Desktop.
Save fiote/3433b1ad5c7f12a55534ce989e88552f to your computer and use it in GitHub Desktop.
const filters = {
tamanho: 'G',
cor: 'red'
};
const validkeys = ['tamanho','cor'];
const wheres = [];
const params = [];
const cases = [];
Object.keys(filters).forEach(key => {
if (!validkeys.includes(key)) return;
cases.push(`(CASE WHEN ${key} = ? THEN 1 ELSE 0 END) match_${key}`);
params.push(filters[key]);
});
Object.keys(filters).forEach(key => {
if (!validkeys.includes(key)) return;
wheres.push(`${key} = ?`);
params.push(filters[key]);
});
const result = await mysql.query(`
SELECT id, ${cases.join(', ')}
FROM camisas
WHERE ${wheres.join(' OR ')}
`, params);
const matches = result.rows.map(row => {
let qtmatches = 0;
Object.keys(filters).forEach(key => {
if (!validkeys.includes(key)) return;
qtmatches += row[`match_${key}`];
});
return qtmatches;
});
console.log(matches);
// [2,1,0];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment