Advertisement
Guest User

Untitled

a guest
Nov 25th, 2016
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. function startApp() {
  3.  
  4.     const kinveyBaseUrl = "https://baas.kinvey.com/";
  5.     const kinveyAppKey = "kid_SkJltdBfl";
  6.     const kinveyAppSecret =
  7.         "4292f7c2fdc94ae6a2682923f9222627";
  8.     const kinveyAppAuthHeaders = {
  9.         'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
  10.     };
  11.  
  12.     sessionStorage.clear(); // Clear user auth data
  13.  
  14.     showHideMenuLinks();
  15.     showView('viewHome');
  16.  
  17.     // Bind the navigation menu links
  18.     $("#linkHome").click(showHomeView);
  19.     $("#linkLogin").click(showLoginView);
  20.     $("#linkRegister").click(showRegisterView);
  21.     $("#linkListAds").click(listAds);
  22.     $("#linkCreateAd").click(showCreateAdView);
  23.     $("#linkLogout").click(logoutUser);
  24.  
  25.     // Bind the form submit buttons
  26.     $("#buttonLoginUser").click(loginUser);
  27.     $("#buttonRegisterUser").click(registerUser);
  28.     $("#buttonCreateAd").click(createAd);
  29.     $("#buttonEditAd").click(editAd);
  30.  
  31.     // Bind the info / error boxes: hide on click
  32.     $("#infoBox, #errorBox").click(function () {
  33.         $(this).fadeOut();
  34.     });
  35.  
  36.     function showHideMenuLinks() {
  37.         $("#linkHome").show();
  38.         if (sessionStorage.getItem('authToken')) {
  39.             // We have logged in user
  40.             $("#linkLogin").hide();
  41.             $("#linkRegister").hide();
  42.             $("#linkListAds").show();
  43.             $("#linkCreateAd").show();
  44.             $("#linkLogout").show();
  45.         } else {
  46.             // No logged in user
  47.             $("#linkLogin").show();
  48.             $("#linkRegister").show();
  49.             $("#linkListAds").hide();
  50.             $("#linkCreateAd").hide();
  51.             $("#linkLogout").hide();
  52.         }
  53.     }
  54.  
  55.     function showView(viewName) {
  56.         // Hide all views and show the selected view only
  57.         $('main > section').hide();
  58.         $('#' + viewName).show();
  59.     }
  60.  
  61.     function showHomeView() {
  62.         showView('viewHome');
  63.     }
  64.  
  65.     function showLoginView() {
  66.         showView('viewLogin');
  67.         $('#formLogin').trigger('reset');
  68.     }
  69.  
  70.     function showRegisterView() {
  71.         $('#formRegister').trigger('reset');
  72.         showView('viewRegister');
  73.     }
  74.  
  75.     function showCreateAdView() {
  76.         $('#formCreateAd').trigger('reset');
  77.         showView('viewCreateAd');
  78.     }
  79.  
  80.     function listAds() {
  81.         $('#ads').empty();
  82.         showView('viewAds');
  83.         $.ajax({
  84.             method: "GET",
  85.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts",
  86.             headers: getKinveyUserAuthHeaders(),
  87.             success: loadAdsSuccess,
  88.             error: handleAjaxError
  89.         });
  90.  
  91.         function loadAdsSuccess(ads) {
  92.             showInfo('Adverts loaded.');
  93.             if (ads.length == 0) {
  94.                 $('#ads').text('No ads in the library.');
  95.             } else {
  96.                 let adsTable = $('<table>')
  97.                     .append($('<tr>').append(
  98.                         '<th>Title</th><th>Description</th>',
  99.                         '<th>Publisher</th><th>Date Published</th>',
  100.                         '<th>Price</th><th>Actions</th>'));
  101.                 for (let ad of ads)
  102.                     appendAdRow(ad, adsTable);
  103.                 $('#ads').append(adsTable);
  104.             }
  105.         }
  106.  
  107.         function appendAdRow(ad, adsTable) {
  108.             let links = [];
  109.             if (ad._acl.creator == sessionStorage['userId']) {
  110.                 let deleteLink = $('<a href="#">[Delete]</a>')
  111.                     .click(function () {
  112.                         deleteAd(ad)
  113.                     });
  114.                 let editLink = $('<a href="#">[Edit]</a>')
  115.                     .click(function () {
  116.                         loadAdForEdit(ad)
  117.                     });
  118.                 links = [deleteLink, ' ', editLink];
  119.             }
  120.  
  121.             adsTable.append($('<tr>').append(
  122.                 $('<td>').text(ad.title),
  123.                 $('<td>').text(ad.description),
  124.                 $('<td>').text(ad.publisher),
  125.                 $('<td>').text(ad.date),
  126.                 $('<td>').text(ad.price),
  127.                 $('<td>').append(links)
  128.             ));
  129.         }
  130.     }
  131.  
  132.     function createAd() {
  133.         let adData = {
  134.             title: $('#formCreateAd input[name=title]').val(),
  135.             description: $('#formCreateAd textarea[name=description]').val(),
  136.             publisher: sessionStorage.getItem('username'),
  137.             date: $('#formCreateAd input[name=datePublished]').val(),
  138.             price: Math.round($('#formCreateAd input[name=price]').val() * 100) / 100
  139.         };
  140.         $.ajax({
  141.             method: "POST",
  142.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts",
  143.             headers: getKinveyUserAuthHeaders(),
  144.             data: adData,
  145.             success: createAdSuccess,
  146.             error: handleAjaxError
  147.         });
  148.  
  149.         function createAdSuccess(response) {
  150.             listAds();
  151.             showInfo('Advert created.');
  152.         }
  153.     }
  154.  
  155.     function editAd() {
  156.         let adData = {
  157.             title: $('#formEditAd input[name=title]').val(),
  158.             description: $('#formEditAd textarea[name=description]').val(),
  159.             publisher: sessionStorage.getItem('username'),
  160.             date: $('#formEditAd input[name=datePublished]').val(),
  161.             price: Math.round($('#formEditAd input[name=price]').val() * 100) / 100
  162.         };
  163.         $.ajax({
  164.             method: "PUT",
  165.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts/" + $('#formEditAd input[name=id]').val(),
  166.             headers: getKinveyUserAuthHeaders(),
  167.             data: adData,
  168.             success: editAdSuccess,
  169.             error: handleAjaxError
  170.         });
  171.  
  172.         function editAdSuccess(response) {
  173.             listAds();
  174.             showInfo('Advert edited.');
  175.         }
  176.     }
  177.  
  178.     function deleteAd(ad) {
  179.         $.ajax({
  180.             method: "DELETE",
  181.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts/" + ad._id,
  182.             headers: getKinveyUserAuthHeaders(),
  183.             success: deleteAdSuccess,
  184.             error: handleAjaxError
  185.         });
  186.         function deleteAdSuccess(response) {
  187.             listAds();
  188.             showInfo('Advert deleted.');
  189.         }
  190.     }
  191.  
  192.     function loadAdForEdit(ad) {
  193.  
  194.         let req = {
  195.             method: "GET",
  196.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/adverts/" + ad._id,
  197.             headers: getKinveyUserAuthHeaders()
  198.         };
  199.  
  200.         $.ajax(req)
  201.             .then(loadAdForEditSuccess)
  202.             .catch(handleAjaxError);
  203.  
  204.         function loadAdForEditSuccess(ad) {
  205.             $('#formEditAd input[name=id]').val(ad._id);
  206.             $('#formEditAd input[name=title]').val(ad.title);
  207.             $('#formEditAd textarea[name=description]').val(ad.description);
  208.             $('#formEditAd input[name=datePublished]').val(ad.date);
  209.             $('#formEditAd input[name=price]').val(ad.price);
  210.             showView('viewEditAd');
  211.         }
  212.     }
  213.  
  214.     function loginUser() {
  215.         let userData = {
  216.             username: $('#formLogin input[name=username]').val(),
  217.             password: $('#formLogin input[name=passwd]').val()
  218.         };
  219.         $.ajax({
  220.             method: "POST",
  221.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  222.             headers: kinveyAppAuthHeaders,
  223.             data: userData,
  224.             success: loginSuccess,
  225.             error: handleAjaxError
  226.         });
  227.  
  228.         function loginSuccess(userInfo) {
  229.             saveAuthInSession(userInfo);
  230.             showHideMenuLinks();
  231.             listAds();
  232.             showInfo('Login successful.');
  233.         }
  234.     }
  235.  
  236.     function registerUser() {
  237.         let userData = {
  238.             username: $('#formRegister input[name=username]').val(),
  239.             password: $('#formRegister input[name=passwd]').val()
  240.         };
  241.         $.ajax({
  242.             method: "POST",
  243.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
  244.             headers: kinveyAppAuthHeaders,
  245.             data: userData,
  246.             success: registerSuccess,
  247.             error: handleAjaxError
  248.         });
  249.  
  250.         function registerSuccess(userInfo) {
  251.             saveAuthInSession(userInfo);
  252.             showHideMenuLinks();
  253.             listAds();
  254.             showInfo('User registration successful.');
  255.         }
  256.     }
  257.  
  258.     function logoutUser() {
  259.         sessionStorage.clear();
  260.         $('#loggedInUser').text("");
  261.         showHideMenuLinks();
  262.         showView('viewHome');
  263.         showInfo('Logout successful.');
  264.     }
  265.  
  266.     function saveAuthInSession(userInfo) {
  267.         let userAuth = userInfo._kmd.authtoken;
  268.         sessionStorage.setItem('authToken', userAuth);
  269.         let userId = userInfo._id;
  270.         sessionStorage.setItem('userId', userId);
  271.         let username = userInfo.username;
  272.         sessionStorage.setItem('username', username);
  273.         $('#loggedInUser').text(
  274.             "Welcome, " + username + "!");
  275.     }
  276.  
  277.     function getKinveyUserAuthHeaders() {
  278.         return {
  279.             'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
  280.         };
  281.     }
  282.  
  283.     function handleAjaxError(response) {
  284.         let errorMsg = JSON.stringify(response);
  285.         if (response.readyState === 0)
  286.             errorMsg = "Cannot connect due to network error.";
  287.         if (response.responseJSON &&
  288.             response.responseJSON.description)
  289.             errorMsg = response.responseJSON.description;
  290.         showError(errorMsg);
  291.     }
  292.  
  293.     function showInfo(message) {
  294.         $('#infoBox').text(message);
  295.         $('#infoBox').show();
  296.         setTimeout(function () {
  297.             $('#infoBox').fadeOut();
  298.         }, 3000);
  299.     }
  300.  
  301.     function showError(errorMsg) {
  302.         $('#errorBox').text("Error: " + errorMsg);
  303.         $('#errorBox').show();
  304.     }
  305. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement