Removing data - DELETE

The final stop on our whirlwind tour of the different REST API HTTP verbs is DELETE. It should be no surprise that sending a DELETE request should do exactly what it sounds like. Let's add another route that accepts DELETE requests and deletes an item from our movies collection. Here is the code that takes care of the DELETE requests, which should be placed after the existing block of code from the previous PUT:

router.delete('/:id', (req, res)=>{ 
    let indexToDel = -1; 
    _.each(json, (elem, index)=>{ 
        if (elem.Id === req.params.id) { 
            indexToDel = index; 
        } 
    }); 
    if (~indexToDel) { 
        json.splice(indexToDel, 1); 
    } 
    res.json(json); 
}); 

This code will loop through the collection of movies and find a matching item by comparing the values of Id. If a match is found, the array index for the matched item is held until the loop is finished. Using the array.splice function, we can remove an array item at a specific index. Once the data has been updated by removing the requested item, the JSON data is returned. Notice that in the following screenshot the updated JSON that's returned is in fact no longer displaying the original second item we deleted:

The ~ use in JavaScript! That's a little bit of JavaScript black magic! The tilde (~) in JavaScript will bit flip a value. In other words, it will take a value and return the negative of that value incremented by one, that is ~n === -(n+1). Typically, the tilde is used with functions that return -1 as a false response. By using ~ on -1, you are converting it to 0. If you were to perform a Boolean check on -1 in JavaScript, it would return true. You will see that ~ is primarily used with the indexOf function and jQuery's $.inArray(); both return -1 as a false response.

All of the endpoints defined in this chapter are extremely rudimentary, and most of these should never see the light of day in a production environment! Whenever you have an API that accepts anything other than GET requests, you need to be sure to enforce extremely strict validation and authentication rules. After all, you are basically giving your users direct access to your data.

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

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