My API serves JSON data. Currently, accessing api/weapons
will provide all available weapons, while api/weapons/weaponName
gives information about a specific weapon. My goal is to filter results using parameters like
api/weapons?type=sword&rarity=5
. I have managed to filter by type and rarity individually with api/weapons?type=sword
and api/weapons?rarity=5
but not together.
This is my current approach:
let filtered = [];
if (query.type) {
filtered = filtered.concat((await weapons).filter(w => formatName(w.weaponType) === formatName(query.type)));
}
if (query.rarity) {
filtered = filtered.concat((await weapons).filter(w => w.rarity == query.rarity));
}
if (!filtered.length) filtered = [await weapons];
res.status(HttpStatusCodes.ACCEPTED).send(filtered);
formatName
is simply a function that converts a string to lowercase, trims it, and removes spaces.
If we consider the example
api/weapons?type=sword&rarity=5
, the current behavior is:
- Retrieve all weapons of type "sword"
- Retrieve all weapons with rarity "5"
- Combine both sets of results, showing all swords regardless of rarity and all weapons with rarity 5 regardless of type.
I aim to only display weapons that match both the specified rarity AND type criteria, such as swords with a rarity of 5. What would be the most efficient way to achieve this filtering?