CRUD: You Just Got Served (Server Communication)

chukwuma1976

Chukwuma Anyadike

Posted on February 13, 2023

CRUD: You Just Got Served (Server Communication)

In this post I am talking about CRUD operations in server communication. During server communication there is communication between the client (also known as the frontend) and the server (also known as the backend);

client server relationship

The client and server communicate through HTTP (Hypertext Transfer Protocol). HTTP is the language browsers speak. Like any language HTTP contains verbs. These verbs correspond to each letter of CRUD and they include POST, GET, UPDATE, and DELETE respectively.

When we want to communicate with the server we use these verbs. In JavaScript we use fetch requests. Let me break it down for you.

This is the boilerplate code for a fetch request.

    fetch('http://domain_name/path', configurationObject)
    .then(response => response.json())
    .then(data => manipulate(data));
Enter fullscreen mode Exit fullscreen mode

The first line fetch('http://domain_name/path', configurationObject) takes one or two arguments. The first argument is a URL (uniform resource locator) which is where the request is sent. The second argument is a configuration object which is used in POST, PATCH, and DELETE requests. It is not used in GET requests. This configuration object contains three attributes.

  1. Method which is either POST, PATCH, or DELETE.
  2. Headers (do not forget the 's') which is defines the content type as JSON (JavaScript Object Notation).
  3. Body which JSON.stringify(object) means to take the object (information being transmitted as key: value pairs) and convert it to JSON format.
const configurationObject = {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify(object)
            }
Enter fullscreen mode Exit fullscreen mode

The first line of a fetch request returns a Promise object which resolves to a Response. The next line .then(response => response.json()) takes that Response object and converts it from JSON to a consumable object. The last line .then(data => manipulate(data)) takes the data object and uses it for DOM manipulation.

Now that I have finished talking about fetch lets talk about CRUD.

The "R" in CRUD is Read. The HTTP verb is GET.

I will talk about this first since it is easy and then we can slowly increase the difficulty. Here is an example below.

    fetch('http://localhost:9292/muscles')
    .then(response => response.json())
    .then(data => setMuscles(data));
Enter fullscreen mode Exit fullscreen mode

This fetch sends a GET request to the URL 'http://localhost:9292/muscles' and obtains data which is passed into a function setMuscles. The data received is typically an array of objects.

The "C" is create. The HTTP verb is POST.

Here we create data and request that it get POSTed to the server.

const newMuscle = {
 name: "deltoid",
 origin: "lateral one-third of the clavicle, acromion, the lower lip of the crest of the spine of the scapula",
 insertion: "deltoid tuberosity of the humerus",
 action: "abducts arm; anterior fibers flex & medially rotate the arm; posterior fibers extend & laterally rotate the arm",
 innervation: "axillary nerve (C5,6)",
 blood_supply: "posterior circumflex humeral a." 
}

fetch("http://localhost:9292/muscles", {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify(newMuscle)
            })
            .then(res=>res.json())
            .then(muscle=>setMuscles([...muscles, muscle]))
Enter fullscreen mode Exit fullscreen mode

This fetch request is a little more complicated since we now have to pass a configuration object as an argument. This configuration object contains our HTTP verb and data (newMuscle) that we want to persist to the server at "http://localhost:9292/muscles". Notice that we still expect to receive data to do our DOM manipulation. The data that we receive is similar to the newMuscle object that we sent but now it has a unique id number assigned to it. It looks like this.

data  = {
 id: (some unique number) //note that a new id number has been assigned
 name: "deltoid",
 origin: "lateral one-third of the clavicle, acromion, the lower lip of the crest of the spine of the scapula",
 insertion: "deltoid tuberosity of the humerus",
 action: "abducts arm; anterior fibers flex & medially rotate the arm; posterior fibers extend & laterally rotate the arm",
 innervation: "axillary nerve (C5,6)",
 blood_supply: "posterior circumflex humeral a." 
}
Enter fullscreen mode Exit fullscreen mode

The "U" is update. The HTTP verb is PATCH.

Here we update data and request that it get PATCHed in the server.

fetch(`http://localhost:9292/muscles/${muscle.id}`, {
                method: "PATCH",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify({action: "elevate scapula"})
            })
            .then(res=>res.json())
            .then(muscle=>onUpdate(muscle))
        closePopUp()
Enter fullscreen mode Exit fullscreen mode

This fetch request is similar to a POST request since we still have to pass a configuration object as an argument. However, this time we are changing an existing object on the server at "http://localhost:9292/muscles" by changing one or more attributes. Note that an id number is required to find which object needs to be updated.

The "D" is delete. The HTTP verb is DELETE.

This one is really easy. A request is made to DELETE data.

        fetch(`http://localhost:9292/muscles/${id}`, {
            method: "DELETE"
        })
        .then(res=>res.json()) //this does not return anything
        .then(()=>onDelete(id)) //manipulate the DOM
Enter fullscreen mode Exit fullscreen mode

All you really need is a URL, id number, and method of DELETE. However, I use the last line to do DOM manipulation.

In summary:

  • Create: POST
  • Read: GET
  • Update: UPDATE
  • Delete: DELETE

With this post the CRUD movie trilogy is complete. However, I'm sure we will see CRUD again as we journey into the domain of writing code.

💖 💪 🙅 🚩
chukwuma1976
Chukwuma Anyadike

Posted on February 13, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related