CRUD App - Update (POST)
Now that the "Edit Player" page loads properly, all that's left is making it actually update the player data. Create a handler function that updates the database, and hook it up to the /edit/:id POST endpoint.
NOTE: Using a POST request instead of a PUT request here is kind of cheating, but it simplifies things and works just as well for our purposes.
Hooking up an "Edit Player" Request Handler
The "Edit Player" request handler will work very similarly to the "Add Player" handler, just with an existing player ID.
- In the routes/player.js file, add a new module export property named
editPlayer- Make sure to add a comma after the
editPlayerPagefunction
- Make sure to add a comma after the
- Set the value of
editPlayerto be a function withrequestandresponseas parameters - In the body of the
editPlayerfunction, logrequest.bodyto the console - After the console log, redirect to the homepage with
response.redirect('/') - In the app.js file, under the
app.postroutes add anotherapp.postto hook up theeditPlayerfunction to the/edit/:idroute:app.post('/edit/:id', player.editPlayer);
Load up the "Edit Player" page for one of the players, submit the form, and verify that the form data is properly logged in the console!
Handling the POST Data
Now that the data is properly in the back-end, it's time to put it in the database. Update the db.js and routes/player.js files to make this happen.
DB Function
Start by creating a function that can edit an existing player's data in the database.
- In the db.js file, add a new module export property named
editPlayerById - Set the value of
editPlayerByIdto be anasyncfunction withplayerIdandplayerObjas parameters - In the body of the
editPlayerByIdfunction, calldb.setonplayerIdandplayerObj- This will set the value in the DB to the new value
- Use the
awaitkeyword in front of thedb.setto properly wait for the result
Code
editPlayerById: async function(playerId, newPlayerObj) {
await db.set(playerId, newPlayerObj);
}
Route Function
Next, update the /edit/:id POST handler to use the DB function to update the data in the DB. Open the routes/player.js file to begin.
- In the
editPlayerfunction, remove theconsole.log - In its place, create a new variable named
playerId - Set
playerIdtorequest.params.id - Under that, add a call to
db.editPlayerById, passing inplayerIdandrequest.body - Put the
awaitkeyword in front ofdb.editPlayerByIdto wait for it to return - Add the
asynckeyword in front of theeditPlayerfunction because it uses anawait
Code
editPlayer: async function (request, response) {
let playerId = request.params.id;
await db.editPlayerById(playerId, request.body);
response.redirect('/');
}
Testing
At this point, it should be fully possible to edit Player data in the database.
- Run the app, and click on the "Edit" button for an existing player
- Enter new information about the player
- Click the "Update Player" button
- Verify that the homepage loads with the new information!