Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function startApp() {
  2.     let navMenu = $('#menu').find('a').show();
  3.     const adsDiv = $('#ads');
  4.  
  5.     function showView(view) {
  6.         $('section').hide();
  7.  
  8.         switch (view) {
  9.             case 'home' :
  10.                 $('#viewHome').show();
  11.                 break;
  12.             case 'login':
  13.                 $('#viewLogin').show();
  14.                 break;
  15.             case 'ads':
  16.                 $('#viewAds').show();
  17.                 loadAds();
  18.                 break;
  19.             case 'create':
  20.                 $('#viewCreateAd').show();
  21.                 break;
  22.             case 'edit':
  23.                 $('#viewEditAd').show();
  24.                 break;
  25.             case 'register':
  26.                 $('#viewRegister').show();
  27.                 break;
  28.  
  29.         }
  30.     }
  31.  
  32.     //  function navigateTo(e) {
  33.     //  $('section').hide();
  34.     //   let target = $(e.target).attr('data-target');
  35.     //    $('#' + target).show(); // # + target made the ID off sections
  36.     // $('header').find('a[data-target]').click(navigateTo);
  37.     //  }
  38.  
  39.     //Attach eventlissenerss
  40.     $('#buttonLoginUser').click(login);
  41.     $('#buttonRegisterUser').click(register);
  42.     $('#buttonCreateAd').click(createAdd);
  43.  
  44.     $('#linkHome').click(() => showView('home'));
  45.     $('#linkListAds').click(() => showView('ads'));
  46.     $('#linkLogin').click(() => showView('login'));
  47.     $('#linkRegister').click(() => showView('register'));
  48.     $('#linkCreateAd').click(() => showView('create'));
  49.     $('#linkLogout').click(logout);
  50.  
  51.  
  52.     $('.notification').click((e) => {
  53.         $(e.target).hide();
  54.     });
  55.  
  56.  
  57.     //Notifications
  58.     $(document).on({
  59.         ajaxStart: () => $('#loadingBox').show(),
  60.         ajaxStop: () => $('#loadingBox').fadeOut()
  61.     });
  62.     $('#infoBox').click((event) => $(event.target).hide());
  63.     $('#errorBox').click((event) => $(event.target).hide());
  64.  
  65.     function showinfo(message) {
  66.         $('#infoBox').text(message);
  67.         $('#infoBox').show();
  68.         setTimeout(() => $('#infoBox').fadeOut(), 3000);
  69.     }
  70.  
  71.     function showErorr(message) {
  72.         $('#errorBox').text(message);
  73.         $('#errorBox').show();
  74.     }
  75.  
  76.     function handleErorr(reason) {
  77.         showErorr(reason.responseJSON.description);
  78.     }
  79.  
  80.     let requester = (() => {
  81.  
  82.         const appKey = 'kid_SkEwdIPPZ';
  83.         const appSecret = '5d676270c6cb4bfbbd706ca6a34f2199';
  84.         const baseUrl = 'https://baas.kinvey.com/';
  85.  
  86.         function makeAuth(type) {
  87.             if (type === 'basic') return 'Basic ' + btoa(appKey + ':' + appSecret);
  88.             else return 'Kinvey ' + localStorage.getItem('authtoken');
  89.         }
  90.  
  91.         function makeRequest(method, module, url, auth) {
  92.             return req = {
  93.                 url: baseUrl + module + '/' + appKey + '/' + url,
  94.                 method,
  95.                 headers: {
  96.                     'Authorization': makeAuth(auth)
  97.                 }
  98.             };
  99.         }
  100.  
  101.         function get(module, url, auth) {
  102.             return $.ajax(makeRequest('GET', module, url, auth));
  103.         }
  104.  
  105.         function post(module, url, data, auth) {
  106.             let req = makeRequest('POST', module, url, auth);
  107.             req.data = JSON.stringify(data); // maby without JSON.stringify
  108.             req.headers['Content-Type'] = 'application/json'; // Whith dis made ERORR for parrsing
  109.             return $.ajax(req);
  110.         }
  111.  
  112.         function update(module, url, data, auth) {
  113.             let req = makeRequest('PUT', module, url, auth);
  114.             req.data = JSON.stringify(data);
  115.             req.headers['Content-Type'] = 'application/json';
  116.             return $.ajax(req);
  117.         }
  118.  
  119.         function remuve(module, url, auth) {
  120.             return $.ajax(makeRequest('DELETE', module, url, auth));
  121.         }
  122.  
  123.         return {
  124.             get, post, update, remuve
  125.         }
  126.     })();  // "HAND SHAKE"//requester.get('appdata','','basic')
  127.  
  128.     if (localStorage.getItem('username') !== null && localStorage.getItem('authtoken')) {
  129.         userLogedIn();
  130.     } else {
  131.         userLogedOuth()
  132.     }
  133.  
  134.     showView('home');
  135.  
  136.     function userLogedIn() {
  137.         $('#loggedInUser').text(`Welcome,  ${localStorage.getItem('username')}!`).show();
  138.  
  139.         $('#linkLogin').hide();
  140.         $('#linkRegister').hide();
  141.         $('#linkLogout').show();
  142.         $('#linkListAds').show();
  143.         $('#linkCreateAd').show();
  144.     }
  145.  
  146.     function userLogedOuth() {
  147.         $('#loggedInUser').text('');
  148.  
  149.         $('#linkLogin').show();
  150.         $('#linkRegister').show();
  151.         $('#linkLogout').hide();
  152.         $('#linkListAds').hide();
  153.         $('#linkCreateAd').hide();
  154.     }
  155.  
  156.     function saveSession(data) {
  157.         localStorage.setItem('username', data.username);
  158.         localStorage.setItem('id', data._id);
  159.         localStorage.setItem('authtoken', data._kmd.authtoken);
  160.         userLogedIn();
  161.     }
  162.  
  163.     async function login() {
  164.         let form = $('#formLogin');
  165.         let username = form.find('input[name="username"]').val();
  166.         let password = form.find('input[name="passwd"]').val();
  167.  
  168.         try {
  169.             let data = await requester.post('user', 'login', {username, password}, 'basic');
  170.             saveSession(data);
  171.             showView('ads');
  172.             showinfo('Logged in')
  173.         } catch (err) {
  174.             handleErorr(err)
  175.         }
  176.     }
  177.  
  178.     async function register(data) {
  179.         let form = $('#formRegister');
  180.         let username = form.find('input[name="username"]').val();
  181.         let password = form.find('input[name="passwd"]').val();
  182.  
  183.         try {
  184.             let data = await requester.post('user', '', {username, password}, 'basic');
  185.             saveSession(data);
  186.             showView('ads')
  187.             showinfo('Registered');
  188.         } catch (err) {
  189.             console.log(err.responseText)
  190.         }
  191.     }
  192.  
  193.     async function logout() {
  194.         try {
  195.             let data = await requester.post('user', '_logout', {authtoken: localStorage.getItem('authtoken')});
  196.             localStorage.clear();
  197.             showView('home');
  198.             userLogedOuth();
  199.             showinfo('Logged out')
  200.  
  201.         } catch (err) {
  202.             handleErorr(err)
  203.         }
  204.  
  205.     }
  206.  
  207.     async function loadAds() {
  208.         let data = await requester.get('appdata', 'posts');
  209.         adsDiv.empty();
  210.  
  211.         if (data.length === 0) {
  212.             adsDiv.append('<p>No ads in database</p>')
  213.         }
  214.  
  215.         for (let ad of data) {
  216.             let html = $('<div>');
  217.             html.addClass('ad-box');
  218.             let title = $(`<div class="add-title">${ad.title}</div>`);
  219.  
  220.             if (ad._acl.creator === localStorage.getItem('id')) {
  221.                 let deleteBtn = $('<button>&#10006;</button>').click(() => deleteAd(ad._id))
  222.                 deleteBtn.appendTo(title);
  223.                 deleteBtn.addClass('ad-control')
  224.  
  225.                 let editBtn = $('<button>&#9998;</button>').click(() => openEditAdd(ad))
  226.                 editBtn.appendTo(title);
  227.                 editBtn.addClass('ad-control');
  228.             }
  229.  
  230.             html.append(title);
  231.             html.append(`<div><img src="${ad.imageurl}"</div>`);
  232.             html.append(`<div>Price : ${ad.price} | By ${ad.publisher}</div>`);
  233.             html.append(`<div>Description : ${ad.description}</div>`);
  234.             adsDiv.append(html)
  235.         }
  236.     }
  237.  
  238.     async function deleteAd(id) {
  239.         await requester.remuve('appdata', 'posts/' + id);
  240.         showinfo('Add Deleted!');
  241.         showView('ads');
  242.     }
  243.  
  244.     function openEditAdd(ad) {
  245.         let form = $('#formEditAd');
  246.         form.find('input[name="title"]').val(ad.title);
  247.         form.find('textarea[name="description"]').val(ad.description);
  248.         form.find('input[name="price"]').val(ad.price);
  249.         form.find('input[name="image"]').val(ad.imageurl);
  250.  
  251.         let date = ad.date;
  252.         let publisher = ad.publisher;
  253.         let id = ad._id;
  254.  
  255.         form.find('#buttonEditAd').click(() => editAd(id, date, publisher));
  256.         showView('edit')
  257.     }
  258.  
  259.     async function editAd(id, date, publisher) {
  260.         let form = $('#formEditAd');
  261.         let title = form.find('input[name="title"]').val();
  262.         let description = form.find('textarea[name="description"]').val();
  263.         let price = form.find('input[name="price"]').val();
  264.         let imageUrl = form.find('input[name="image"]').val();
  265.  
  266.         if (title.length == 0) {
  267.             showErorr("Title cannot by empty!");
  268.             return;
  269.         }
  270.         if (price.length == 0) {
  271.             showErorr("Title cannot by empty!");
  272.             return;
  273.         }
  274.  
  275.         let editedAdd = {
  276.             title, description, price, imageUrl, date, publisher
  277.         };
  278.  
  279.         try {
  280.             await requester.update('appdata', 'posts/', + id, editedAdd);
  281.             showinfo('Ad editted');
  282.         }
  283.         catch (err) {
  284.             console.log(id);
  285.             handleErorr(err);
  286.  
  287.         }
  288.  
  289.     }
  290.  
  291.     async function createAdd() {
  292.         let form = $('#formCreateAd');
  293.         let title = form.find('input[name="title"]').val();
  294.         let description = form.find('textarea[name="description"]').val();
  295.         let price = form.find('input[name="price"]').val();
  296.         let imageurl = form.find('input[name="image"]').val();
  297.  
  298.         let date = new Date();
  299.         date = "" + date.getDate() + "." + date.getMonth() + "." + date.getFullYear();
  300.         let publisher = localStorage.getItem('username');
  301.  
  302.         if (title.length == 0) {
  303.             showErorr("Title cannot by empty!");
  304.             return;
  305.         }
  306.         if (price.length == 0) {
  307.             showErorr("Title cannot by empty!");
  308.             return;
  309.         }
  310.  
  311.         let newAd = {
  312.             title, description, price, imageurl, date, publisher
  313.         };
  314.  
  315.         try {
  316.             await requester.post('appdata', 'posts', newAd);
  317.             showinfo('Ad created')
  318.         }
  319.         catch (err) {
  320.             handleErorr(err);
  321.         }
  322.  
  323.     }
  324.  
  325. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement