Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by Merrie on 12/20/16.
- */
- function startApp() {
- const kinveyBaseUrl = "https://baas.kinvey.com/";
- const kinveyAppKey = "kid_BkgrHyPNx";
- const kinveyAppSecret = "0a80d7870a094292ab4f8e89484ccf62";
- const kinveyAppAuthHeaders = {
- 'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
- };
- //Hide status boxes
- $('#infoBox').hide();
- $('#errorBox').hide();
- $('#loadingBox').hide();
- sessionStorage.clear(); // Clear user auth data
- showHideMenuLinks();
- if(sessionStorage.getItem('authToken')) {
- $('#spanMenuLoggedInUser').text('Welcome, ' + sessionStorage.getItem('name') + '!');
- showUserHomeView()
- }else {
- $('#spanMenuLoggedInUser').empty();
- showAppHomeView();
- }
- //Bind menu links with views
- $("#linkMenuAppHome").click(showAppHomeView);
- $("#linkMenuLogin").click(showLoginView);
- $("#linkMenuRegister").click(showRegisterView);
- $("#linkMenuUserHome").click(showUserHomeView);
- $("#linkMenuShop").click(showShopView);
- $("#linkMenuCart").click(showCartView);
- $("#linkMenuLogout").click(logoutUser);
- // Bind the form submit buttons
- $(`#formLogin input[type="submit"]`).click(loginUser);
- $(`#formRegister input[type="submit"]`).click(registerUser);
- $("#infoBox, #errorBox").click(function () {
- $(this).fadeOut();
- });
- // Attach AJAX "loading" event listener
- $(document).on({
- ajaxStart: function () {
- $("#loadingBox").show()
- },
- ajaxStop: function () {
- $("#loadingBox").hide()
- }
- });
- function showHideMenuLinks() {
- if (sessionStorage.getItem('authToken')) {
- // We have logged in user
- $("#linkMenuAppHome").hide();
- $("#linkMenuLogin").hide();
- $("#linkMenuRegister").hide();
- $("#linkMenuUserHome").show();
- $("#linkMenuShop").show();
- $("#linkMenuCart").show();
- $("#linkMenuLogout").show();
- } else {
- // No logged in user
- $("#linkMenuAppHome").show();
- $("#linkMenuLogin").show();
- $("#linkMenuRegister").show();
- $("#linkMenuUserHome").hide();
- $("#linkMenuShop").hide();
- $("#linkMenuCart").hide();
- $("#linkMenuLogout").hide();
- }
- }
- function showView(viewName) {
- // Hide all views and show the selected view only
- $('main > section').hide();
- $('#' + viewName).show();
- }
- function showAppHomeView() {
- //Bind the user home buttons
- $("#linkUserHomeShop").click(showShopView);
- $("#linkUserHomeCart").click(showCartView);
- showView('viewAppHome');
- }
- function showUserHomeView() {
- $('#viewUserHomeHeading').text('Welcome, ' + sessionStorage.getItem('name') + '!');
- showView('viewUserHome');
- }
- function showLoginView() {
- showView('viewLogin');
- $('#formLogin').trigger('reset');
- }
- function showRegisterView() {
- $('#formRegister').trigger('reset');
- showView('viewRegister');
- }
- function showShopView() {
- $('#viewShop').empty();
- const getShopUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/products`;
- let table = $('<table>').append(
- `<thead>
- <tr>
- <th>Product</th>
- <th>Description</th>
- <th>Price</th>
- <th>Actions</th>
- </tr>
- </thead>`);
- $.ajax({
- method: "GET",
- url: getShopUrl,
- headers: getKinveyUserAuthHeaders(),
- success: fillTable,
- error: handleAjaxError
- });
- function fillTable(products) {
- if (products.length == 0) {
- $('#viewShop').empty();
- $('#viewShop').text('No products found.')
- }
- else {
- let tbody = $('<tbody>');
- for (let prd of products) {
- let prcBtn = $('<button>').text("Purchase");
- prcBtn.click(x => purchaseProduct(prd._id));
- tbody.append($('<tr>')
- .append($(`<td>`).text(prd.name))
- .append($(`<td>`).text(prd.description))
- .append($(`<td>`).text(prd.price.toFixed(2)))
- .append($('<td>').append(prcBtn)));
- }
- table.append(tbody);
- $('#viewShop').empty();
- $('#viewShop').append(table);
- }
- }
- showView('viewShop');
- }
- function showCartView() {
- $('#viewCart').empty();
- const getCartUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/shoppingCart`;
- let table = $('<table>').append(
- `<thead>
- <tr>
- <th>Product</th>
- <th>Description</th>
- <th>Quantity</th>
- <th>Total Price</th>
- <th>Actions</th>
- </tr>
- </thead>`);
- $.ajax({
- method: "GET",
- url: getCartUrl,
- headers: getKinveyUserAuthHeaders(),
- success: fillTable,
- error: handleAjaxError
- });
- function fillTable(products) {
- if (products.length == 0) {
- $('#viewCart').empty();
- $('#viewCart').text('No products found.')
- }
- else {
- let tbody = $('<tbody>');
- for (let prd of products) {
- let prcBtn = $('<button>').text("Discard");
- prcBtn.click(x => discardProduct(prd._id));
- tbody.append($('<tr>')
- .append($(`<td>`).text(prd.name))
- .append($(`<td>`).text(prd.description))
- .append($('<td>').text(prd.quantity))
- .append($(`<td>`).text(prd.totalPrice.toFixed(2)))
- .append($('<td>').append(prcBtn)));
- }
- table.append(tbody);
- $('#viewCart').empty();
- $('#viewCart').append(table);
- }
- }
- showView('viewCart');
- }
- function purchaseProduct(id) {
- let cartUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/shoppingCart";
- $.ajax({
- method: "GET",
- url: cartUrl,
- headers: getKinveyUserAuthHeaders(),
- success: successGet,
- error: handleAjaxError
- });
- function successGet(data){
- data = data.filter(x => x.UserId == userId && x.ProductId == id);
- if(data){
- data[0].Quantity = Number(data[0].Quantity) + 1;
- $.ajax({
- method: "PUT",
- url: cartUrl,
- headers: getKinveyUserAuthHeaders(),
- body: JSON.stringify(data[0])
- });
- } else {
- let productData = {
- UserId: sessionStorage.getItem('userId'),
- ProductId: id,
- Quantity: 1
- };
- $.ajax({
- method: "POST",
- url: cartUrl,
- data: productData,
- headers: getKinveyUserAuthHeaders(),
- success: purchaseSuccess,
- error: handleAjaxError
- });
- }
- }
- function purchaseSuccess(){
- showInfo('Product purchased.');
- }
- }
- function loginUser(newUser) {
- newUser.preventDefault();
- let userData = {
- username: $('#loginUsername').val(),
- password: $('#loginPasswd').val()
- };
- $.ajax({
- method: "POST",
- url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
- headers: kinveyAppAuthHeaders,
- data: userData,
- success: loginSuccess,
- error: handleAjaxError
- });
- function loginSuccess(userInfo) {
- saveAuthInSession(userInfo);
- showHideMenuLinks();
- $('#spanMenuLoggedInUser').text("Welcome, " + sessionStorage.getItem('name') + '!');
- showUserHomeView();
- showInfo('Login successful.');
- }
- }
- function registerUser(newUser) {
- newUser.preventDefault();
- let userData = {
- username: $('#registerUsername').val(),
- password: $('#registerPasswd').val(),
- name: $('#registerName').val()
- };
- $.ajax({
- method: "POST",
- url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
- headers: kinveyAppAuthHeaders,
- data: userData,
- success: registerSuccess,
- error: handleAjaxError
- });
- function registerSuccess(userInfo) {
- saveAuthInSession(userInfo);
- showHideMenuLinks();
- showUserHomeView();
- showInfo('User registration successful.');
- }
- }
- function logoutUser() {
- sessionStorage.clear();
- $('#spanMenuLoggedInUser').empty();
- showHideMenuLinks();
- showView('viewAppHome');
- showInfo('Logout successful.');
- }
- function getKinveyUserAuthHeaders() {
- return {
- 'Authorization': "Kinvey " +
- sessionStorage.getItem('authToken'),
- };
- }
- function saveAuthInSession(userInfo) {
- let userAuth = userInfo._kmd.authtoken;
- sessionStorage.setItem('authToken', userAuth);
- let userId = userInfo._id;
- sessionStorage.setItem('userId', userId);
- let username = userInfo.username;
- sessionStorage.setItem('username', username);
- let name = userInfo.name;
- sessionStorage.setItem('name', name);
- $('#loggedInUser').text(
- "Welcome, " + username + "!");
- }
- function handleAjaxError(response) {
- let errorMsg = JSON.stringify(response);
- if (response.readyState === 0)
- errorMsg = "Cannot connect due to network error.";
- if (response.responseJSON &&
- response.responseJSON.description)
- errorMsg = response.responseJSON.description;
- showError(errorMsg);
- }
- function showInfo(message) {
- $('#infoBox').text(message);
- $('#infoBox').show();
- setTimeout(function () {
- $('#infoBox').fadeOut();
- }, 2000);
- }
- function showError(errorMsg) {
- $('#errorBox').text("Error: " + errorMsg);
- $('#errorBox').show();
- setTimeout(function () {
- $('#errorBox').fadeOut();
- }, 2000);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement