Why check if an id exists in the expressions array?



Why check if an id exists in the expressions array?


We might think that if the id parameter does not exist in our array, by default it will just not update anything, and in a way we are correct, but it will still try and it will return a 200 ok. For example, there is no expression with id 20, if we run the server we can get 1:
06%20AM 15%20AM

Yet, if we try as well with an id of 20:

OF COURSE, as expected! Now, if we just set up our PUT request to update the array without checking if the item already exists, we can update the first item:

the problem comes when trying to update with the id of 20:

It somehow shows success, but two things:
One, the item does not exist, and two, it wasn’t really updated.

PUT does have to create capabilities, but since the expressions are items in an array, an array (in JavaScript) cannot get a new item without using the .push() method, so the assignment is not successful but the operation and succeeding actions are still performed, returning a 200 Ok success response.

Therefore, the main reason for us to check if an id exists before any action is been performed is that otherwise, it would become an expensive transaction. No matter how fast a computer is, time is still of the escence, in this case, yes the user might receive the data in time, but it is an update that never happened, so the user just wasted some time and it makes it to be a bug in our code, while also thinking that any proccess in a hosted server is usually either charged by the operation or by the time an operation takes, then the fact that we are running a function regardless if the item even exists will costs us (or the company we work for) real money every time. We want to be effective, and we want our API method request handlers to be as efficient as possible. That is why, it is important to check for values received in the query if they are the type needed for the action, and if the item requested exists.

FAQ: Learn Express Routes - Using Queries