Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function startApp() {
- let navMenu = $('#menu').find('a').show();
- const adsDiv = $('#ads');
- function showView(view) {
- $('section').hide();
- switch (view) {
- case 'home' :
- $('#viewHome').show();
- break;
- case 'login':
- $('#viewLogin').show();
- break;
- case 'ads':
- $('#viewAds').show();
- loadAds();
- break;
- case 'create':
- $('#viewCreateAd').show();
- break;
- case 'edit':
- $('#viewEditAd').show();
- break;
- case 'register':
- $('#viewRegister').show();
- break;
- }
- }
- // function navigateTo(e) {
- // $('section').hide();
- // let target = $(e.target).attr('data-target');
- // $('#' + target).show(); // # + target made the ID off sections
- // $('header').find('a[data-target]').click(navigateTo);
- // }
- //Attach eventlissenerss
- $('#buttonLoginUser').click(login);
- $('#buttonRegisterUser').click(register);
- $('#buttonCreateAd').click(createAdd);
- $('#linkHome').click(() => showView('home'));
- $('#linkListAds').click(() => showView('ads'));
- $('#linkLogin').click(() => showView('login'));
- $('#linkRegister').click(() => showView('register'));
- $('#linkCreateAd').click(() => showView('create'));
- $('#linkLogout').click(logout);
- $('.notification').click((e) => {
- $(e.target).hide();
- });
- //Notifications
- $(document).on({
- ajaxStart: () => $('#loadingBox').show(),
- ajaxStop: () => $('#loadingBox').fadeOut()
- });
- $('#infoBox').click((event) => $(event.target).hide());
- $('#errorBox').click((event) => $(event.target).hide());
- function showinfo(message) {
- $('#infoBox').text(message);
- $('#infoBox').show();
- setTimeout(() => $('#infoBox').fadeOut(), 3000);
- }
- function showErorr(message) {
- $('#errorBox').text(message);
- $('#errorBox').show();
- }
- function handleErorr(reason) {
- showErorr(reason.responseJSON.description);
- }
- let requester = (() => {
- const appKey = 'kid_SkEwdIPPZ';
- const appSecret = '5d676270c6cb4bfbbd706ca6a34f2199';
- const baseUrl = 'https://baas.kinvey.com/';
- function makeAuth(type) {
- if (type === 'basic') return 'Basic ' + btoa(appKey + ':' + appSecret);
- else return 'Kinvey ' + localStorage.getItem('authtoken');
- }
- function makeRequest(method, module, url, auth) {
- return req = {
- url: baseUrl + module + '/' + appKey + '/' + url,
- method,
- headers: {
- 'Authorization': makeAuth(auth)
- }
- };
- }
- function get(module, url, auth) {
- return $.ajax(makeRequest('GET', module, url, auth));
- }
- function post(module, url, data, auth) {
- let req = makeRequest('POST', module, url, auth);
- req.data = JSON.stringify(data); // maby without JSON.stringify
- req.headers['Content-Type'] = 'application/json'; // Whith dis made ERORR for parrsing
- return $.ajax(req);
- }
- function update(module, url, data, auth) {
- let req = makeRequest('PUT', module, url, auth);
- req.data = JSON.stringify(data);
- req.headers['Content-Type'] = 'application/json';
- return $.ajax(req);
- }
- function remuve(module, url, auth) {
- return $.ajax(makeRequest('DELETE', module, url, auth));
- }
- return {
- get, post, update, remuve
- }
- })(); // "HAND SHAKE"//requester.get('appdata','','basic')
- if (localStorage.getItem('username') !== null && localStorage.getItem('authtoken')) {
- userLogedIn();
- } else {
- userLogedOuth()
- }
- showView('home');
- function userLogedIn() {
- $('#loggedInUser').text(`Welcome, ${localStorage.getItem('username')}!`).show();
- $('#linkLogin').hide();
- $('#linkRegister').hide();
- $('#linkLogout').show();
- $('#linkListAds').show();
- $('#linkCreateAd').show();
- }
- function userLogedOuth() {
- $('#loggedInUser').text('');
- $('#linkLogin').show();
- $('#linkRegister').show();
- $('#linkLogout').hide();
- $('#linkListAds').hide();
- $('#linkCreateAd').hide();
- }
- function saveSession(data) {
- localStorage.setItem('username', data.username);
- localStorage.setItem('id', data._id);
- localStorage.setItem('authtoken', data._kmd.authtoken);
- userLogedIn();
- }
- async function login() {
- let form = $('#formLogin');
- let username = form.find('input[name="username"]').val();
- let password = form.find('input[name="passwd"]').val();
- try {
- let data = await requester.post('user', 'login', {username, password}, 'basic');
- saveSession(data);
- showView('ads');
- showinfo('Logged in')
- } catch (err) {
- handleErorr(err)
- }
- }
- async function register(data) {
- let form = $('#formRegister');
- let username = form.find('input[name="username"]').val();
- let password = form.find('input[name="passwd"]').val();
- try {
- let data = await requester.post('user', '', {username, password}, 'basic');
- saveSession(data);
- showView('ads')
- showinfo('Registered');
- } catch (err) {
- console.log(err.responseText)
- }
- }
- async function logout() {
- try {
- let data = await requester.post('user', '_logout', {authtoken: localStorage.getItem('authtoken')});
- localStorage.clear();
- showView('home');
- userLogedOuth();
- showinfo('Logged out')
- } catch (err) {
- handleErorr(err)
- }
- }
- async function loadAds() {
- let data = await requester.get('appdata', 'posts');
- adsDiv.empty();
- if (data.length === 0) {
- adsDiv.append('<p>No ads in database</p>')
- }
- for (let ad of data) {
- let html = $('<div>');
- html.addClass('ad-box');
- let title = $(`<div class="add-title">${ad.title}</div>`);
- if (ad._acl.creator === localStorage.getItem('id')) {
- let deleteBtn = $('<button>✖</button>').click(() => deleteAd(ad._id))
- deleteBtn.appendTo(title);
- deleteBtn.addClass('ad-control')
- let editBtn = $('<button>✎</button>').click(() => openEditAdd(ad))
- editBtn.appendTo(title);
- editBtn.addClass('ad-control');
- }
- html.append(title);
- html.append(`<div><img src="${ad.imageurl}"</div>`);
- html.append(`<div>Price : ${ad.price} | By ${ad.publisher}</div>`);
- html.append(`<div>Description : ${ad.description}</div>`);
- adsDiv.append(html)
- }
- }
- async function deleteAd(id) {
- await requester.remuve('appdata', 'posts/' + id);
- showinfo('Add Deleted!');
- showView('ads');
- }
- function openEditAdd(ad) {
- let form = $('#formEditAd');
- form.find('input[name="title"]').val(ad.title);
- form.find('textarea[name="description"]').val(ad.description);
- form.find('input[name="price"]').val(ad.price);
- form.find('input[name="image"]').val(ad.imageurl);
- let date = ad.date;
- let publisher = ad.publisher;
- let id = ad._id;
- form.find('#buttonEditAd').click(() => editAd(id, date, publisher));
- showView('edit')
- }
- async function editAd(id, date, publisher) {
- let form = $('#formEditAd');
- let title = form.find('input[name="title"]').val();
- let description = form.find('textarea[name="description"]').val();
- let price = form.find('input[name="price"]').val();
- let imageUrl = form.find('input[name="image"]').val();
- if (title.length == 0) {
- showErorr("Title cannot by empty!");
- return;
- }
- if (price.length == 0) {
- showErorr("Title cannot by empty!");
- return;
- }
- let editedAdd = {
- title, description, price, imageUrl, date, publisher
- };
- try {
- await requester.update('appdata', 'posts/', + id, editedAdd);
- showinfo('Ad editted');
- }
- catch (err) {
- console.log(id);
- handleErorr(err);
- }
- }
- async function createAdd() {
- let form = $('#formCreateAd');
- let title = form.find('input[name="title"]').val();
- let description = form.find('textarea[name="description"]').val();
- let price = form.find('input[name="price"]').val();
- let imageurl = form.find('input[name="image"]').val();
- let date = new Date();
- date = "" + date.getDate() + "." + date.getMonth() + "." + date.getFullYear();
- let publisher = localStorage.getItem('username');
- if (title.length == 0) {
- showErorr("Title cannot by empty!");
- return;
- }
- if (price.length == 0) {
- showErorr("Title cannot by empty!");
- return;
- }
- let newAd = {
- title, description, price, imageurl, date, publisher
- };
- try {
- await requester.post('appdata', 'posts', newAd);
- showinfo('Ad created')
- }
- catch (err) {
- handleErorr(err);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement