JavaScript Frontend UI

This database was setup to allow people to HaHa or Boohoo a collection of Computer Jokes. The entirety has lot of limitation.

  • People can vote more than once and in both categories.
  • There is no auto refresh if several are voting and updating as you are looking at your static page.
  • Perhaps Q and A style could hide punch line.
  • Perhaps we could accept new jokes, or have interface for adding them.

Amazingly, though … the front-end code is in a completely different project. The front end project GETs and PUTs using the back end APIs. The key element that makes this different than other public APIs, like RapidAPI, is the “reaction” function. This function updates the elementID of the like or jeer as soon as you impact the button.

Frontend JavaScript Code

// Reaction function to likes or jeers user actions
  function reaction(type, put_url, elemID) {

    // fetch the API
    fetch(put_url, put_options)
    // response is a RESTful "promise" on any successful fetch
    .then(response => {
      // check for response errors
      if (response.status !== 200) {
          error("PUT API response failure: " + response.status)
          return;  // api failure
      }
      // valid response will have JSON data
      response.json().then(data => {
          console.log(data);
          // Likes or Jeers updated/incremented
          if (type === HAHA) // like data element
            document.getElementById(elemID).innerHTML = data.haha;  // fetched haha data assigned to haha Document Object Model (DOM)
          else if (type === BOOHOO) // jeer data element
            document.getElementById(elemID).innerHTML = data.boohoo;  // fetched boohoo data assigned to boohoo Document Object Model (DOM)
          else
            error("unknown type: " + type);  // should never occur
      })
    })
    // catch fetch errors (ie Nginx ACCESS to server blocked)
    .catch(err => {
      error(err + " " + put_url);
    });
    
  }