Created
June 30, 2022 23:45
-
-
Save fiote/3433b1ad5c7f12a55534ce989e88552f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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