Updating the Scores

To update the score, we will require the ID of the match to look up for an existing one. If a valid match is found, we will apply the updates. If no match is found, we have to respond with a 404 not found HTTP response. Otherwise, we respond with a Success 200 HTTP response.

Let's start by creating the updateScore function, as shown:

...
const Match = require('../models/match')

const updateScore = async (matchId, teamId) => {
try {
let match = await Match.findById(matchId)

if (match == null) throw new Error("Match not found")

if (teamId == 'team_1') {
match.score.team_1++;
} else {
match.score.team_2++;
}

match = await match.save()
return match

} catch (err) {
throw err
}
}


api
.route('/admin/match/:id?')
...

Now, let's call our function in the PUT HTTP verb, as illustrated:

...
api
.route('/admin/match/:id?')
.post((req, res, next) => {
...
})
api
.route('/admin/match/scores/:id')
.post((req, res, next) => {

const matchId = req.params.id
const teamId = req.body.teamId

updateScore(matchId, teamId)
.then(match => res.json(match))
.catch(err => next(err))
})
...

Cool! Let's test things out. Execute the following curl command to update the match we created earlier:

$ curl -X POST -H "Content-type: application/json" -d '{"teamId": "team_1" }'  localhost:3000/admin/match/scores/5a94a2b8221bb505c92d801c

{"_id":"5a94a2b8221bb505c92d801c","team_1":"Peru","team_2":"Chile","__v":0,"score":{"team_1":21,"team_2":0}}

Note that the team_1 (Peru team) now has 21 goals in its score, and the Chile team has 0.

Awesome! Now we are able to create a new Match and update the scores. Let's use express-jwt and express-jwt-permissions to secure our APIs. Keep reading!

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

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