Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import 'bootstrap/dist/css/bootstrap.css'
  2. import { isNullOrUndefined } from 'util';
  3. document.addEventListener("DOMContentLoaded", function () {
  4.     /*---------- Begin Get Person By Name ---------*/
  5.     /*----- Should be moved to NavBar function ----*/
  6.     fillViewPersonWithDataDiv();
  7.     fillViewAllPersonsWithDataDiv()
  8.     document.getElementById("viewPersonWithDataButtonTAG").addEventListener('click', function (event) {
  9.         event.preventDefault();
  10.         singleuser();
  11.     });
  12.     document.getElementById("viewAllPersonsWithDataButtonTAG").addEventListener('click', function (event) {
  13.         event.preventDefault();
  14.         allUsersToPtag();
  15.         allUsersToTableTag();
  16.     });
  17. });
  18.  
  19. const url = 'https://maltemagnussen.com/CA2/api/search/';
  20. const testurl = 'http://localhost:8080/CA2/api/search/';
  21.  
  22. function handleHttpErrors(res) {
  23.     if (!res.ok) {
  24.         return Promise.reject({ status: res.status, fullError: res.json() })
  25.     }
  26.     return res.json();
  27. }
  28.  
  29. /*---------------------------------------------*/
  30. /*---------- Begin Get Person By Name ---------*/
  31. /*---------------------------------------------*/
  32.  
  33. function fillViewPersonWithDataDiv() {
  34.     emptyDiv('viewPersonWithData');
  35.     let ptag = document.createElement('p');
  36.     ptag.setAttribute('id', 'viewPersonWithDataPTAG');
  37.  
  38.     let inputtag = document.createElement('input');
  39.     inputtag.setAttribute('id', 'viewPersonWithDataInputTAG');
  40.     inputtag.setAttribute('type', 'text');
  41.     inputtag.setAttribute('placeholder', 'UserName');
  42.  
  43.     let buttontag = document.createElement('button');
  44.     buttontag.innerHTML = 'Get User';
  45.     buttontag.setAttribute('id', 'viewPersonWithDataButtonTAG');
  46.  
  47.     let div = document.getElementById('viewPersonWithData');
  48.     div.appendChild(inputtag);
  49.     div.appendChild(buttontag);
  50.     div.appendChild(ptag);
  51. }
  52.  
  53. /*---- To clear the div of data ---*/
  54. function emptyDiv(divID) {
  55.     let div = document.getElementById(divID);
  56.     div.innerHTML = "";
  57. }
  58.  
  59. function singleuser() {
  60.     let username = document.getElementById('viewPersonWithDataInputTAG').value;
  61.     if (!username) {
  62.         document.getElementById('viewPersonWithDataPTAG').innerHTML = 'Type in a name'
  63.     }
  64.     else {
  65.         let urlName = url + 'person/' + username;
  66.         fetch(urlName)
  67.             .then(handleHttpErrors)
  68.             .then(fetchedData => {
  69.                 document.getElementById('viewPersonWithDataPTAG').innerHTML = writeToPTagPrPerson(fetchedData[0]);
  70.             })
  71.             .catch(err => {
  72.                 if (err.status) {
  73.                     err.fullError.then(e => console.log(e.detail))
  74.                 }
  75.                 else { console.log("Network error"); }
  76.             });
  77.     }
  78. }
  79.  
  80. function writeToPTagPrPerson(jsondata) {
  81.     let hobbies = '';
  82.     jsondata['hobbies'].forEach(element => {
  83.         hobbies = hobbies + '<br>' + element.name + ' - ' + element.description;
  84.     });
  85.     let phones = '';
  86.     jsondata['phones'].forEach(element => {
  87.         phones = phones + '<br>' + element.description + ': ' + element.number;
  88.     });
  89.  
  90.     let stringToWrite =
  91.         "<br>Firstname: " + jsondata['firstName'] + ' ' + jsondata['lastName']
  92.         + "<br>e-mail: " + jsondata['email'];
  93.     if (!isNullOrUndefined(jsondata['address'])) {
  94.         stringToWrite = stringToWrite + "<br>Address: " + jsondata['address']['street'] + ', '
  95.             + jsondata['address']['additionalInfo'] + ', ' + jsondata['address']['cityInfo']['zipCode']
  96.             + ' ' + jsondata['address']['cityInfo']['city'];
  97.     }
  98.     stringToWrite = stringToWrite
  99.         + "<br>Hobbies: " + hobbies
  100.         + "<br>Phones: " + phones;
  101.     return stringToWrite;
  102. }
  103.  
  104. /*---------------------------------------------*/
  105. /*----------- End Get Person By Name ----------*/
  106. /*---------------------------------------------*/
  107.  
  108. /*---------- Begin Add Person Simple ----------*/
  109. /*---------------------------------------------*/
  110.  
  111. var output = document.getElementById("output");
  112.  
  113. var buttonAddSimple = document.getElementById("createSimplePerson");
  114.  
  115. buttonAddSimple.addEventListener("click", function () {
  116.     fetch(url + "create/person", createPersonOptions())
  117.         .then(res => handleHttpErrors(res))
  118.         .then(function (data) {
  119.             console.log(data);
  120.             output.innerHTML = "<p>Person created:</p><br>"
  121.                 + "<p>ID: " + data.id + "<br>"
  122.                 + "<p>First name: " + data.firstName + "<br>"
  123.                 + "<p>Last name: " + data.lastName + "<br>"
  124.                 + "<p>email: " + data.email + "<br>";
  125.         })
  126.         .catch(err => {
  127.             if (err.status) {
  128.                 err.fullError.then(e => output.innerHTML = "Error:<br><br>")
  129.             }
  130.             else { console.log("Network error"); }
  131.         });
  132. })
  133.  
  134. function createPersonOptions() {
  135.     var FirstName = document.getElementById("inputFirstName").value;
  136.     var LastName = document.getElementById("inputLastName").value;
  137.     var Email = document.getElementById("inputEmail").value;
  138.     var Method = "POST";
  139.     var data = {
  140.         firstName: FirstName,
  141.         lastName: LastName,
  142.         email: Email
  143.     }
  144.  
  145.     let options = {
  146.         method: Method,
  147.         headers: {
  148.             'Accept': 'application/json',
  149.             'Content-Type': 'application/json'
  150.         },
  151.         body: JSON.stringify(data)
  152.     }
  153.     console.log(options);
  154.     return options;
  155. }
  156.  
  157. /*---------------------------------------------*/
  158. /*----------- End Add Person Simple -----------*/
  159. /*---------------------------------------------*/
  160.  
  161. /*---------------------------------------------*/
  162. /*----------- Begin Get All Persons -----------*/
  163. /*---------------------------------------------*/
  164.  
  165. function fillViewAllPersonsWithDataDiv() {
  166.     emptyDiv('viewAllPersonsWithData');
  167.     let ptag = document.createElement('p');
  168.     ptag.setAttribute('id', 'viewAllPersonsWithDataPTAG');
  169.  
  170.     let buttontag = document.createElement('button');
  171.     buttontag.innerHTML = 'Get All Users';
  172.     buttontag.setAttribute('id', 'viewAllPersonsWithDataButtonTAG');
  173.  
  174.     let tabletag = document.createElement('table');
  175.     tabletag.setAttribute('id', 'viewAllPersonsWithDataTableTAG');
  176.  
  177.     let div = document.getElementById('viewAllPersonsWithData');
  178.     div.appendChild(buttontag);
  179.     div.appendChild(ptag);
  180.     div.appendChild(tabletag);
  181. }
  182.  
  183. function allUsersToPtag() {
  184.     let urlAll = url + 'allpersons';
  185.     fetch(urlAll)
  186.         .then(handleHttpErrors)
  187.         .then(jsondata => {
  188.  
  189.             let allPersonsToWrite = '';
  190.  
  191.             jsondata.forEach(element => {
  192.                 allPersonsToWrite = allPersonsToWrite + writeToPTagPrPerson(element);
  193.             });
  194.             document.getElementById('viewAllPersonsWithDataPTAG').innerHTML = allPersonsToWrite;
  195.         })
  196.         .catch(err => {
  197.             if (err.status) {
  198.                 err.fullError.then(e => console.log(e.detail))
  199.             }
  200.             else { console.log("Network error: " + err); }
  201.         });
  202. }
  203.  
  204. function allUsersToTableTag() {
  205.     let urlAll = url + 'allpersons';
  206.     fetch(urlAll)
  207.         .then(handleHttpErrors)
  208.         .then(jsondata => {
  209.             let table = document.getElementById('viewAllPersonsWithDataTableTAG');
  210.             let headdata = Object.keys(jsondata[0]);
  211.             tableHead(table, headdata);
  212.             tableData(table, jsondata);
  213.             fixTableHeaders();
  214.  
  215.         })
  216.         .catch(err => {
  217.             if (err.status) {
  218.                 err.fullError.then(e => console.log(e.detail))
  219.             }
  220.             else { console.log("Network error: " + err); }
  221.         });
  222. }
  223.  
  224. function tableHead(table, headData) {
  225.     let head = table.createTHead();
  226.     let row = head.insertRow();
  227.     for (let key of headData) {
  228.         let th = document.createElement("th");
  229.         let text = document.createTextNode(key);
  230.         th.id = key;
  231.         th.appendChild(text);
  232.         row.appendChild(th);
  233.     }
  234.  
  235. }
  236.  
  237. function tableData(table, bodyData) {
  238.     let tbody = document.createElement('tbody');
  239.     table.appendChild(tbody);
  240.     for (let element of bodyData) {
  241.         let row = table.insertRow();
  242.         tbody.appendChild(row);
  243.         for (let key in element) {
  244.             let cell = row.insertCell();
  245.             let obj = JSON.parse(JSON.stringify(element));
  246.             let cellValue = '';
  247.             if (typeof element[key] === 'object') {
  248.                 if(key === 'address'){
  249.                     cellValue = obj.address.street + ', ' + obj.address.cityInfo.zipCode + ' ' + obj.address.cityInfo.city;
  250.                 }
  251.                 else if(key === 'hobbies'){
  252.                     obj.hobbies.forEach(hobby => {
  253.                         cellValue = cellValue + hobby.name + ', ';
  254.                     });
  255.                     cellValue = cellValue.slice(0, -2);
  256.                 }
  257.                 else if(key === 'phones'){
  258.                     obj.phones.forEach(phone => {
  259.                         cellValue = cellValue + phone.description + ': ' + phone.number + ', ';
  260.                     });
  261.                     cellValue = cellValue.slice(0, -2);
  262.                 }
  263.             }
  264.             else {
  265.                 cellValue = element[key];
  266.             }
  267.             let text = document.createTextNode(cellValue);
  268.             cell.appendChild(text);
  269.         }
  270.     }
  271. }
  272.  
  273. function fixTableHeaders(){
  274.     document.getElementById("address").innerText = "Address";
  275.     document.getElementById("email").innerText = "E-mail";
  276.     document.getElementById("firstName").innerText = "Firstname";
  277.     document.getElementById("id").innerText = "ID";
  278.     document.getElementById("lastName").innerText = "Lastname";
  279.     document.getElementById("phones").innerText = "Phone numbers";
  280.     document.getElementById("hobbies").innerText = "Hobbies";
  281.    
  282. }
  283.  
  284. /*---------------------------------------------*/
  285. /*------------ End Get All Persons ------------*/
  286. /*---------------------------------------------*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement