Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function startApp() {
- sessionStorage.clear();
- $(document).on('ajaxStart', function () {
- $("#loadingBox").show()
- });
- $(document).on('ajaxStop', function () {
- $("#loadingBox").hide()
- });
- function showInfo(message) {
- $("#infoBox > span").text(message);
- $("#infoBox").show();
- setTimeout(function () {
- $("#infoBox").hide()
- }, 3000)
- }
- function attachBoxesEvents() {
- $('#errorBox').on('click', function () {
- $(this).hide()
- });
- $('#infoBox').on('click', function () {
- $(this).hide()
- })
- }
- function showError(message) {
- $("#errorBox > span").text(message)
- $("#errorBox").show();
- setTimeout(function () {
- $("#errorBox").hide()
- }, 3000)
- }
- function handleAjaxError(response) {
- let errorMessage = JSON.stringify(response);
- if (response.readyState === 0) {
- let errorMessage = 'Cannot connect due to network error.'
- }
- if (response.responseJSON && response.responseJSON.description) {
- errorMessage = response.responseJSON.description;
- }
- showError(errorMessage);
- }
- const BASE_URL = 'https://baas.kinvey.com/';
- const APP_KEY = 'kid_Bk9LMjklE';
- const APP_SECRET = 'ba8a5b60c0224fceb24f93c1eeebf36a';
- const AUTH_HEADERS = {'Authorization': "Basic " + btoa(APP_KEY + ":" + APP_SECRET)};
- function saveAuthInSession(userInfo) {
- sessionStorage.setItem('authToken', userInfo._kmd.authtoken);
- sessionStorage.setItem('userId', userInfo._id);
- sessionStorage.setItem('userName', userInfo.username);
- }
- function signInUser(res, message) {
- saveAuthInSession(res);
- showInfo(message);
- showHome();
- }
- $('form').submit(function (event) {
- event.preventDefault();
- });
- showHome();
- attachBoxesEvents();
- $('#home').on('click', showHome);
- $('#showLogin').on('click', showLogin);
- $('#signIn').on('click', showLogin);
- $('#showRegister').on('click', showRegister);
- $('#signUp').on('click', showRegister);
- $('#submitRegister').on('click', submitRegister);
- $('#submitLogin').on('click', submitLogin);
- $('#logout').on('click', logout);
- $('#allListings').on('click', showCarListings);
- $('#createListing').on('click', showCreateListing);
- $('#submitListing').on('click', submitListing);
- $('#myListings').on('click', showMyListings);
- function hideAllViews() {
- $('#allListings').hide();
- $('#myListings').hide();
- $('#createListing').hide();
- $('#profile').hide();
- $('#main').hide();
- $('#login').hide();
- $('#register').hide();
- $('#car-listings').hide();
- $('#create-listing').hide();
- $('#edit-listing').hide();
- $('#myCarListings').hide();
- $('#listingDetails').hide();
- }
- function showHideLinks() {
- hideAllViews();
- if (sessionStorage.getItem('authToken')){
- $('#allListings').show();
- $('#myListings').show();
- $('#createListing').show();
- $('#profile').show();
- $('#greeting').text(`Welcome, ${sessionStorage.getItem('userName')}`);
- }
- }
- function showHome() {
- showHideLinks();
- if (sessionStorage.getItem('authToken')){
- showCarListings();
- } else {
- $('#main').show();
- }
- }
- function showLogin() {
- showHideLinks();
- $('#login').show();
- }
- function showRegister() {
- showHideLinks();
- $('#register').show();
- }
- function submitRegister() {
- let username = $('#usernameRegisterInput').val().trim();
- let password = $('#passwordRegisterInput').val().trim();
- let repeatPassword = $('#repeatPasswordRegisterInput').val().trim();
- let usernameRegex = /[A-Za-z]{3,}$/;
- let passwordRegex = /[A-Za-z0-9]{6,}$/;
- if (!usernameRegex.test(username.toString())) {
- showError('Username should be at least 3 characters long and contain only English alphabet letters.');
- } else if (!passwordRegex.test(password.toString())) {
- showError('Password should be at least 6 characters long and contain only English alphabet letters and digits.')
- } else if (password !== repeatPassword) {
- showError('Passwords do not match.')
- } else {
- $.ajax({
- method: "POST",
- url: BASE_URL + 'user/' + APP_KEY + '/',
- headers: AUTH_HEADERS,
- data: {username, password}
- }).then(function (res) {
- signInUser(res, 'Registration successful.');
- $('#formRegister').trigger('reset')
- }).catch(handleAjaxError);
- }
- }
- function submitLogin() {
- let username = $('#usernameLoginInput').val().trim();
- let password = $('#passwordLoginInput').val().trim();
- $.ajax({
- method: 'POST',
- url: BASE_URL + 'user/' + APP_KEY + '/login',
- headers: AUTH_HEADERS,
- data: {username, password}
- }).then(function (res) {
- signInUser(res, 'Login successful.');
- $('#formLogin').trigger('reset')
- }).catch(handleAjaxError)
- }
- function logout() {
- $.ajax({
- method: 'POST',
- url: BASE_URL + 'user/' + APP_KEY + '/_logout',
- headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')}
- }).catch(function (err) {
- console.log(err)
- });
- sessionStorage.clear();
- showHome();
- showInfo("Logout successful");
- }
- function showCarListings() {
- showHideLinks();
- $.ajax({
- method: 'GET',
- url: BASE_URL + 'appdata/' + APP_KEY + '/cars?query={}&sort={"_kmd.ect": -1}',
- headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')},
- }).then(function (res) {
- listResponse(res);
- }).catch(handleAjaxError);
- function listResponse(res) {
- $('#listings').empty();
- if (res.length === 0){
- $('#listings').append($('<p class="no-cars">No cars in database.</p>'));
- } else {
- for (const car of res) {
- let bigDiv = $('<div class="listing"></div>');
- bigDiv.append($(`<p>${car.title}</p>
- <img src="${car.imageUrl}">
- <h2>Brand: ${car.brand}</h2>`));
- let infoDiv = $('<div class="info"></div>');
- infoDiv.append($(`<div id="data-info">
- <h3>Seller: ${car.seller}</h3>
- <h3>Fuel: ${car.fuel}</h3>
- <h3>Year: ${car.year}</h3>
- <h3>Price: ${car.price} $</h3>
- </div>`));
- let dataButtons = $('<div id="data-buttons"></div>');
- let ul = $('<ul></ul>');
- let detailsButton = $('<li class="action"><a href="#" class="button-carDetails" id="detailsButton">Details</a></li>')
- .on('click', function () {
- showDetails(car);
- });
- let editButton = $('<li class="action"><a href="#" class="button-carDetails" id="editButton">edit</a></li>')
- .on('click', function () {
- showEditListing(car);;
- });
- let deleteButton = $('<li class="action"><a href="#" class="button-carDetails" id="deleteButton">delete</a></li>')
- .on('click', function () {
- deleteListing(car);
- });
- if (sessionStorage.getItem('userName') === car.seller){
- ul.append(detailsButton);
- ul.append(editButton);
- ul.append(deleteButton);
- } else {
- ul.append(detailsButton);
- }
- dataButtons.append(ul);
- infoDiv.append(dataButtons);
- bigDiv.append(infoDiv);
- $('#listings').append(bigDiv);
- }
- }
- $('#car-listings').show();
- }
- }
- function showCreateListing() {
- showHideLinks();
- $('#create-listing').show();
- }
- function showMyListings() {
- showHideLinks();
- $('#myCars').empty();
- $.ajax({
- method: 'GET',
- url: BASE_URL + 'appdata/' + APP_KEY + `/cars?query={"_acl.creator":"${sessionStorage.getItem("userId")}"}`,
- headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')},
- }).then(function (res) {
- listResponse(res);
- }).catch(handleAjaxError);
- function listResponse(res) {
- if (res.length === 0){
- $('#myCars').append('<p class="no-cars"> No cars in database.</p>');
- } else {
- for (const car of res) {
- let bigDiv = $('<div class="my-listing"></div>');
- bigDiv.append($(`<p id="listing-title">${car.title}</p>
- <img src="${car.imageUrl}">
- <div class="listing-props">
- <h2>Brand: ${car.brand}</h2>
- <h3>Model: ${car.model}</h3>
- <h3>Year: ${car.year}</h3>
- <h3>Price: ${car.price}$</h3>
- </div>`));
- let buttons = $('<div class="my-listing-buttons"></div>');
- let detailsButton = $('<a href="#" class="my-button-list">Details</a>')
- .on('click', function () {
- showDetails(car);
- });
- let editButton = $('<a href="#" class="my-button-list">Edit</a>')
- .on('click', function () {
- showEditListing(car);
- });
- let deleteButton = $('<a href="#" class="my-button-list">Delete</a>')
- .on('click', function () {
- deleteListing(car);
- });
- buttons.append(detailsButton);
- buttons.append(editButton);
- buttons.append(deleteButton);
- bigDiv.append(buttons);
- $('#myCars').append(bigDiv);
- }
- }
- $('#myCarListings').show();
- }
- }
- function showDetails(car) {
- showHideLinks();
- $('#listingDetails').empty();
- let bigDiv = $('<div class="my-listing-details">');
- bigDiv.append($(`<p id="listing-title">${car.title}</p>
- <img src="${car.imageUrl}">
- <div class="listing-props">
- <h2>Brand: ${car.brand}</h2>
- <h3>Model: ${car.model}</h3>
- <h3>Year: ${car.year}</h3>
- <h3>Price: ${car.price}$</h3>
- </div>`));
- if (car.seller === sessionStorage.getItem('userName')){
- let buttons = $('<div class="listings-buttons"></div>');
- let editButton = $('<a href="#" class="button-list">Edit</a>')
- .on('click', function () {
- showEditListing(car);
- });
- let deleteButton = $('<a href="#" class="button-list">Delete</a>')
- .on('click', function () {
- deleteListing(car)
- });
- buttons.append(editButton);
- buttons.append(deleteButton);
- bigDiv.append(buttons);
- }
- bigDiv.append($(`<p id="description-title">Description:</p>
- <p id="description-para">${car.description}</p>`));
- $('#listingDetails').append(bigDiv);
- $('#listingDetails').show();
- }
- function submitListing() {
- let seller = sessionStorage.getItem('userName');
- let title = $('#titleAdd').val();
- let description = $('#descriptionAdd').val();
- let imageUrl = $('#urlAdd').val();
- let brand = $('#brandAdd').val();
- let model = $('#modelAdd').val();
- let fuel = $('#fuelAdd').val();
- let year = $('#yearAdd').val();
- let price = $('#priceAdd').val();
- $.ajax({
- method: 'POST',
- url: BASE_URL + 'appdata/' + APP_KEY + '/cars',
- headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')},
- data: {seller, title, description, imageUrl, brand, model, fuel, year, price}
- }).then(function (event) {
- event.preventDefault();
- $('form #createForm').trigger("reset");
- showHome();
- showInfo("Listing created!");
- }).catch(handleAjaxError)
- }
- function showEditListing(car) {
- showHideLinks();
- $('#titleEdit').val(car.title);
- $('#descriptionEdit').val(car.description);
- $('#urlEdit').val(car.imageUrl);
- $('#brandEdit').val(car.brand);
- $('#modelEdit').val(car.model);
- $('#fuelEdit').val(car.fuel);
- $('#yearEdit').val(car.year);
- $('#priceEdit').val(car.price);
- $('#edit-listing').show();
- $('#editListingSubmit').on('click', function (event) {
- event.preventDefault();
- submitEditListing(car);
- });
- }
- function submitEditListing(car) {
- let seller = sessionStorage.getItem('userName');
- let title = $('#titleEdit').val();
- let description = $('#descriptionEdit').val();
- let imageUrl = $('#urlEdit').val();
- let brand = $('#brandEdit').val();
- let model = $('#modelEdit').val();
- let fuel = $('#fuelEdit').val();
- let year = $('#yearEdit').val();
- let price = $('#priceEdit').val();
- let id = car._id;
- $.ajax({
- method: 'PUT',
- url: BASE_URL + 'appdata/' + APP_KEY + '/cars/' + id,
- headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')},
- data: {seller, title, description, imageUrl, brand, model, fuel, year, price}
- }).then(function (res) {
- showInfo("Successfully edited car.");
- $('#editForm').trigger("reset");
- showHome();
- }).catch(handleAjaxError)
- }
- function deleteListing(car) {
- let id = car._id;
- $.ajax({
- method: 'DELETE',
- url: BASE_URL + 'appdata/' + APP_KEY + '/cars/' + id,
- headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')},
- }).then(function () {
- showInfo("Car deleted.");
- showHome();
- }).catch(handleAjaxError)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement