Updating a Team

The update process is a combination of two processes—the search for a team and the update process itself. In the previous implementation, we wrote the code to look up an existing team. So, let's reuse the same code by defining a function that can be used for retrieve, update, and delete. Open the teams-api.js file and apply the following changes:

...
let teams = [
{ id: 1, name: "Peru"},
{ id: 2, name: "Russia"}
]

function lookupTeamIndex(id) {
for(var i = 0; i < teams.length; i++) {
let team = teams[i]
if (team.id == id)
return i
}
return -1
}

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

We created the lookupTeam function, which expects for the id as a param and will return a valid team index if it is found. Otherwise, it will return -1. Now we need to refactor our handle to retrieve a Team:

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

if (index !== -1)
return res.json(teams[index])

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

Having done that, let's implement our update handler. Apply the following changes in the same teams-api file:

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

if (index !== -1) {
const team = teams[index]

team.name = req.body.name
teams[index] = team

return res.json(team)
}

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

So we define a .put route and look up for a team by passing the id param. If a valid index is returned, we save the team instance in the team variable and apply the change to its name property by reading the data from the request.body object and finally, we send the updated team. If there is not a valid index for the ID passed, we return a Not Found message.

Execute the following command to test things out:

$ curl -X PUT -H "Content-Type: application/json" -d '{"name": "Brasil"}' localhost:3000/teams/999

Team not found
..................Content has been hidden....................

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