Advertisement
stanly65

books

Aug 20th, 2017
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function startApp() {
  2.     const kinveyBaseUrl = "https://baas.kinvey.com/";
  3.     const kinveyAppKey = "kid_S1agMOFr";
  4.     const kinveyAppSecret = "f54c4354d4fe43268769694d219be58b";
  5.     const kinveyAppAuthHeaders = {
  6.         "Authorization": "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret)
  7.     };
  8.  
  9.     sessionStorage.clear();
  10.     showHideMenuLinks();
  11.     showView('viewHome');
  12.  
  13.     $('#linkHome').click(showHomeView);
  14.     $('#linkLogin').click(showLoginView);
  15.     $('#linkRegister').click(showRegisterView);
  16.     $('#linkListBooks').click(listBooks);
  17.     $('#linkCreateBook').click(showCreateBookView);
  18.     $('#linkLogout').click(logoutUser);
  19.  
  20.     $('#buttonLoginUser').click(loginUser);
  21.     $('#buttonRegisterUser').click(registerUser);
  22.     $('#buttonCreateBook').click(createBook);
  23.     $('#buttonEditBook').click(editBook);
  24.  
  25.     $('#infoBox, #errorBox').click(function () {
  26.         $(this).fadeOut();
  27.     });
  28.  
  29.     $(document).on({
  30.         ajaxStart: function () {
  31.             $('#loadingBox').show();
  32.         },
  33.         ajaxStop: function () {
  34.             $('#loadingBox').hide();
  35.         }
  36.     });
  37.  
  38.     function showHideMenuLinks() {
  39.         $('#linkHome').show();
  40.  
  41.         if(sessionStorage.getItem('authToken')) {
  42.             $('#linkLogin').hide();
  43.             $('#linkRegister').hide();
  44.             $('#linkListBooks').show();
  45.             $('#linkCreateBook').show();
  46.             $('#linkLogout').show();
  47.         } else {
  48.             $('#linkLogin').show();
  49.             $('#linkRegister').show();
  50.             $('#linkListBooks').hide();
  51.             $('#linkCreateBook').hide();
  52.             $('#linkLogout').hide();
  53.         }
  54.     }
  55.    
  56.     function showView(viewName) {
  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 showCreateBookView() {
  76.         $('#formCreateBook').trigger('reset');
  77.         showView('viewCreateBook');
  78.     }
  79.    
  80.     function loginUser() {
  81.         let userData = {
  82.             username: $('#formLogin input[name=username]').val(),
  83.             password: $('#formLogin input[name=passwd]').val()
  84.         };
  85.  
  86.         $.ajax({
  87.             method: "POST",
  88.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  89.             headers: kinveyAppAuthHeaders,
  90.             data: userData,
  91.             success: loginSuccess,
  92.             error: handleAjaxError
  93.         });
  94.  
  95.         function loginSuccess(userInfo) {
  96.             saveAuthInSession(userInfo);
  97.             showHideMenuLinks();
  98.             listBooks();
  99.             showInfo('Login successful.');
  100.         }
  101.     }
  102.    
  103.     function registerUser() {
  104.         let userData = {
  105.             username: $('#formRegister input[name=username]').val(),
  106.             password: $('#formRegister input[name=passwd]').val()
  107.         };
  108.  
  109.         $.ajax({
  110.             method: "POST",
  111.             url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
  112.             headers: kinveyAppAuthHeaders,
  113.             data: userData,
  114.             success: registerSuccess,
  115.             error: handleAjaxError
  116.         });
  117.        
  118.         function registerSuccess(userInfo) {
  119.             saveAuthInSession(userInfo);
  120.             showHideMenuLinks();
  121.             listBooks();
  122.             showInfo('User registration successful.');
  123.         }
  124.     }
  125.    
  126.     function saveAuthInSession(userInfo) {
  127.         let userAuth = userInfo._kmd.authtoken;
  128.         sessionStorage.setItem('authToken', userAuth);
  129.         let userId = userInfo._id;
  130.         sessionStorage.setItem('userId', userId);
  131.         let username = userInfo.username;
  132.         $('#loggedInUser').text("Welcome, " + username + "!");
  133.     }
  134.    
  135.     function handleAjaxError(response) {
  136.         let errorMsg = JSON.stringify(response);
  137.         if(response.readyState === 0) {
  138.             errorMsg = "Cannot connect due to network error.";
  139.         }
  140.         if(response.responseJSON && response.responseJSON.description) {
  141.             errorMsg = response.responseJSON.description;
  142.         }
  143.  
  144.         showError(errorMsg);
  145.     }
  146.    
  147.     function showInfo(message) {
  148.         $('#infoBox').text(message);
  149.         $('#infoBox').show();
  150.         setTimeout(function () {
  151.             $('#infoBox').fadeOut();
  152.         }, 3000);
  153.     }
  154.    
  155.     function showError(errorMsg) {
  156.         $('#errorBox').text("Error: " + errorMsg);
  157.         $('#errorBox').show();
  158.     }
  159.    
  160.     function logoutUser() {
  161.         sessionStorage.clear();
  162.         $('#loggedInUser').text('');
  163.         showHideMenuLinks();
  164.         showView('viewHome');
  165.         showInfo('Logout successful.')
  166.     }
  167.  
  168.     function listBooks() {
  169.         $('#books').empty();
  170.         showView('viewBooks');
  171.  
  172.         $.ajax({
  173.             method: "GET",
  174.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/books",
  175.             headers: getKinveyUserAuthHeaders(),
  176.             success: loadBooksSuccess,
  177.             error: handleAjaxError
  178.         });
  179.        
  180.         function loadBooksSuccess(books) {
  181.             showInfo('Books loaded.');
  182.             if(books.length === 0) {
  183.                 $('#books').text('No books in the library.');
  184.             } else {
  185.                 let booksTable = $('<table>')
  186.                     .append($('<tr>')
  187.                         .append('<th>Title</th><th>Author</th>', '<th>Description</th><th>Actions</th>'));
  188.  
  189.                 for(let book of books){
  190.                     appendBookRow(book, booksTable);
  191.                 }
  192.  
  193.                 $('#books').append(booksTable)
  194.             }
  195.            
  196.             function appendBookRow(book, booksTable) {
  197.                 let links = [];
  198.                 if(book._acl.creator === sessionStorage['userId']) {
  199.                     let deleteLink = $('<a href="#">[Delete]</a>').click(function () {
  200.                         deleteBook(book);
  201.                     });
  202.                     let editLink = $('<a href="#">[Edit]</a>').click(function () {
  203.                         loadBookForEdit(book);
  204.                     });
  205.  
  206.                     links = [deleteLink, ' ', editLink];
  207.                 }
  208.  
  209.                 booksTable.append($('<tr>')
  210.                     .append($('<td>').text(book.title), $('<td>').text(book.author), $('<td>').text(book.description), $('<td>').append(links)
  211.                     ));
  212.             }
  213.         }
  214.     }
  215.    
  216.     function getKinveyUserAuthHeaders() {
  217.         return {
  218.             "Authorization": "Kinvey " + sessionStorage.getItem('authToken')
  219.         };
  220.     }
  221.    
  222.     function createBook() {
  223.         let bookData = {
  224.             title: $('#formCreateBook input[name=title]').val(),
  225.             author: $('#formCreateBook input[name=author]').val(),
  226.             description: $('#formCreateBook textarea[name=descr]').val()
  227.         };
  228.  
  229.         $.ajax({
  230.             method: "POST",
  231.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/books",
  232.             headers: getKinveyUserAuthHeaders(),
  233.             data: bookData,
  234.             success: createBookSuccess,
  235.             error: handleAjaxError
  236.         });
  237.  
  238.         function createBookSuccess(response) {
  239.             listBooks();
  240.             showInfo('Book created.');
  241.         }
  242.     }
  243.    
  244.     function loadBookForEdit(book) {
  245.         $.ajax({
  246.             method: "GET",
  247.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/books/" + book._id,
  248.             headers: getKinveyUserAuthHeaders(),
  249.             success: loadBookForEditSuccess,
  250.             error: handleAjaxError
  251.         });
  252.  
  253.         function loadBookForEditSuccess(book) {
  254.             $('#formEditBook input[name=id]').val(book._id);
  255.             $('#formEditBook input[name=title]').val(book.title);
  256.             $('#formEditBook input[name=author]').val(book.author);
  257.             $('#formEditBook textarea[name=descr]').val(book.description);
  258.  
  259.             showView('viewEditBook');
  260.         }
  261.     }
  262.    
  263.     function editBook() {
  264.         let bookData = {
  265.             title: $('#formEditBook input[name=title]').val(),
  266.             author: $('#formEditBook input[name=author]').val(),
  267.             description: $('#formEditBook textarea[name=descr]').val()
  268.         };
  269.  
  270.         $.ajax({
  271.             method: "PUT",
  272.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/books/" + $('#formEditBook input[name=id]').val(),
  273.             headers: getKinveyUserAuthHeaders(),
  274.             data: bookData,
  275.             success: editBookSuccess,
  276.             error: handleAjaxError
  277.         });
  278.  
  279.         function editBookSuccess(response) {
  280.             listBooks();
  281.             showInfo('Book edited.');
  282.         }
  283.     }
  284.  
  285.     function deleteBook(book) {
  286.         $.ajax({
  287.             method: "DELETE",
  288.             url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/books/" + book._id,
  289.             headers: getKinveyUserAuthHeaders(),
  290.             success: deleteBookSuccess,
  291.             error: handleAjaxError
  292.         });
  293.        
  294.         function deleteBookSuccess(response) {
  295.             listBooks();
  296.             showInfo('Book deleted.');
  297.         }
  298.     }
  299. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement