The last operation we've defined in our Swagger specification for our to-do API is this put operation. It allows us to update a single to-do by its ID. The parameters it requires on the URL path is the ID of the Todo to be updated, and then in the body is the updated Todo itself.
The Swagger router controller looks for a file named updateTodo by ID, and it's going to try to implement a function called updateTodo by ID, let's build all of that. Inside my Controllers folder, I'll create a new file and we're going to call it updateTodo by ID according to our Swagger specification.
I'm going to require my client, which is my Elasticsearch client that has the configuration details for talking to the Elasticsearch cluster, and I'll export the module and then create that function.
The function has a request and response objects, and then, we'll call the client update method, specify in there the index and the type. The ID number of the Elasticsearch document we're going to be updating, and we're going to get that from the URL path, which can be found on request.swagger.params.id.value.
The way the update for Elasticsearch works is there's a body and inside the body is a doc and that doc contains the updated document for your Elasticsearch cluster. We can find that as updatedTodo.value.
It's worth noting there that the way we've built this is that the client is going to be expected to return the entire Todo back to the server, not just the fields that have changed, otherwise, it's just going to update the Todo, but only with the information that they send. We're going to provide a callback to that to check for when it's complete.
Again, set our header to application/json. Then if that error object exists, we're going to set our status code that we send back as a 400 to indicate there was an error. Then, we'll send back the error itself. Otherwise, it means we have a successful operation. We can just end the response there.
The last thing we need to do is test that it's working, I've used the Todo endpoint to bring up a single Todo of ID number one. I'll use the Swagger editor to do that and I've got the updated Todo filled out here, I can send that request and then refresh my page and the Todo has been updated.