Retrieving the list

We already have the list handler, but the listing is not enough. Apart from retrieving the full list, we will need to retrieve a single team. To do this, we will need to add a new GET route and learn how to use params. Apply the following changes into the teams-api.js:

...
api
.route('/teams')
...

api
.route('/teams/:id')
.get((req, res) => {
const id = req.params.id

for(let team of teams) {
if (team.id == id)
return res.json(team)
}

return res.status(404).send('team not found')
})

module.exports = api

First, we declare a new route, which now contains a dynamic param—/teams/:api. We said dynamic because, of course, it can take any value that will be available as an attribute of the req.params object. Note that the name you use for your param will be created as a property, for example, req.params.id in this case.

Next, we create a simple for loop that iterates across the full list of teams and looks for the team that has the same id we passed in the route param. If a team is found, we send the team by calling the res.json(team) statement. As we want to quit the handler immediately after we send the response, we use return to exit the handler. If a team is not found, we send an error message and mark the response with the HTTP status 404, which means Resource not found.

Lastly, to test our implementation, execute the following command:

$ curl http://localhost:3000/teams/1
{"id":1,"name":"Peru"}

$ curl http://localhost:3000/teams/2
{"id":2,"name":"Russia"}
Keep in mind that by default, curl always sends a -X GET request if no HTTP verb has been explicitly defined.

Let's continue with our last two implementations for PUT and DELETE.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.21.229