Search code examples
node.jsexpresshttpget

RESTful API, http get from couple of keys


I'm new with node.js and I am building a RESTful API. I have the following data:

const matches = [ 
{
home_team: "Sutton United",
home_score: 0,
away_team: "Arsenal",
away_score: 0,
tournament: "fa",
start_time: "Monday 20th February 2017"
},
{
home_team: "Arsenal",
home_score: 0,
away_team: "Chelsea",
away_score: 0,
tournament: "fa",
start_time: "Monday 20th February 2017"
}
];

and I'm trying to get a response of all matches a team participate, no matter if it is home or away. Therefore, when I'm lookin for 'Arsenal', I want to get both matches. My code looks like that:

app.get('/api/matches/:home_team'||'/api/matches/:away_team', (req, res) => {
const match = matches.find(c => (c.home_team === req.params.home_team || c.away_team === req.params.away_team))
if (!match) res.status(404).send('The match with the given id was not found');
res.send(match);});

which doesn't work the way I want. How can I fix it?


Solution

  • use filter instead of find:

    app.get('/api/matches/:team', (req, res) => {
    const match = matches.filter(c => (c.home_team === req.params.team || c.away_team === req.params.team));
    if (!match) 
       res.status(404).send('The match with the given id was not found');
    res.send(match);
    });