Advertisement
Guest User

Untitled

a guest
Dec 19th, 2018
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.51 KB | None | 0 0
  1. function startApp() {
  2. sessionStorage.clear();
  3. hideAll();
  4.  
  5. $('#dashboard-btn').on('click', () => allListings());
  6. $('#my-listings').on('click', myListings);
  7. $('#register-btn').on('click', registerView);
  8. $('#register-submit').on('click', registerSubmit);
  9. $('#login-btn').on('click', loginView);
  10. $('#login-submit').on('click', loginSubmit);
  11. $('#logout-btn').on('click', logout);
  12. $('#create-listing-btn').on('click', createListingView);
  13. $('#create-listing-submit').on('click', createListing);
  14. $('#all').on('click', () => allListings());
  15. $('#cats').on('click', () => allListings("Cat"));
  16. $('#dogs').on('click', () => allListings("Dog"));
  17. $('#parrots').on('click', () => allListings("Parrot"));
  18. $('#reptiles').on('click', () => allListings("Reptile"));
  19. $('#other').on('click', () => allListings("Other"));
  20.  
  21.  
  22. $("form").submit(function (event) {
  23. event.preventDefault()
  24. });
  25.  
  26. $(document).on({
  27. ajaxStart: function () {
  28. $('#loadingBox').show()
  29. },
  30. ajaxStop: function () {
  31. $('#loadingBox').hide()
  32. }
  33. });
  34. $('#infoBox', '#errorBox').on('click', function () {
  35. $(this).fadeOut()
  36. });
  37.  
  38. function showInfo(message) {
  39. $('#infoBox').show();
  40. $('#infoBox > span').text(message);
  41. setTimeout(function () {
  42. $('#infoBox').fadeOut()
  43. }, 3000)
  44. }
  45.  
  46. function showError(error) {
  47. $('#errorBox').show();
  48. $('#errorBox > span').text(error);
  49. $('#errorBox').on('click', function () {
  50. $(this).fadeOut()
  51. })
  52. }
  53.  
  54. function handleAjaxError(response) {
  55. let errorMsg = JSON.stringify(response);
  56. if (response.readyState === 0)
  57. errorMsg = "Cannot connect due to network error.";
  58. if (response.responseJSON && response.responseJSON.description)
  59. errorMsg = response.responseJSON.description;
  60. showError(errorMsg);
  61. }
  62.  
  63. const kinveyBaseUrl = "https://baas.kinvey.com/";
  64. const kinveyAppKey = "kid_B1zmM57e4";
  65. const kinveyAppSecret = "4db957aaa042449e895dbdd9566a6b8b";
  66. const kinveyAppAuthHeaders = {
  67. 'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
  68. };
  69.  
  70. function saveAuthInSession(userInfo) {
  71. sessionStorage.setItem('authToken', userInfo._kmd.authtoken);
  72. sessionStorage.setItem('userId', userInfo._id);
  73. sessionStorage.setItem('userName', userInfo.username);
  74. }
  75.  
  76. function getKinveyUserAuthHeaders() {
  77. return {
  78. 'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
  79. };
  80. }
  81.  
  82. function registerView() {
  83. hideAll();
  84. $('.basic').hide();
  85. $('.register').show();
  86. }
  87.  
  88. function registerSubmit() {
  89. const username = $('.register input[name="username"]').val();
  90. const password = $('.register input[name="password"]').val();
  91.  
  92. if (!username || username.length < 3) {
  93. showError("Username must be at least 3 symbols");
  94. } else if (!password || password.length < 6) {
  95. showError("Password must be at least 6 symbols");
  96. } else {
  97. $.ajax({
  98. method: "POST",
  99. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
  100. headers: kinveyAppAuthHeaders,
  101. data: {username, password}
  102. }).then(function (res) {
  103. saveAuthInSession(res);
  104. $('.register form').trigger('reset');
  105. showHome();
  106. showInfo('User registration successful.');
  107. $('#welcome-message').text(`Welcome ${sessionStorage.getItem('userName')}`);
  108. }).catch(handleAjaxError)
  109. }
  110. }
  111.  
  112. function showHome() {
  113. hideAll();
  114. $('.basic').show();
  115. }
  116.  
  117. function loginView() {
  118. hideAll();
  119. $('.basic').hide();
  120. $('.login').show();
  121. }
  122.  
  123. function loginSubmit() {
  124. const username = $('.login input[name="username"]').val();
  125. const password = $('.login input[name="password"]').val();
  126.  
  127. if (!username || username.length < 3) {
  128. showError("Username must be at least 3 symbols");
  129. } else if (!password || password.length < 6) {
  130. showError("Password must be at least 6 symbols");
  131. } else {
  132. $.ajax({
  133. method: "POST",
  134. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  135. data: {username, password},
  136. headers: kinveyAppAuthHeaders
  137. }).then(function (res) {
  138. saveAuthInSession(res);
  139. hideAll();
  140. showInfo('Login successful.');
  141. showHome();
  142. $('.login form').trigger('reset');
  143. $('#welcome-message').text(`Welcome ${sessionStorage.getItem('userName')}`);
  144. }).catch(handleAjaxError)
  145. }
  146. }
  147.  
  148. function logout() {
  149. $.ajax({
  150. method: "POST",
  151. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/_logout",
  152. headers: getKinveyUserAuthHeaders()
  153. }).then(() => {
  154. sessionStorage.clear();
  155. hideAll();
  156. showInfo('Logout successful.');
  157. }).catch(handleAjaxError)
  158. }
  159.  
  160. function hideAll() {
  161. $('.navbar-dashboard').hide();
  162. $('.navbar-anonymous').hide();
  163. $('.basic').hide();
  164. $('.login').hide();
  165. $('.register').hide();
  166. $('.create').hide();
  167. $('.myPet').hide();
  168. $('.otherPet').hide();
  169. $('.deletePet').hide();
  170. $('.detailsMyPet').hide();
  171. $('.detailsOtherPet').hide();
  172. $('.dashboard').hide();
  173. $('.my-pets').hide();
  174. showMain();
  175. }
  176.  
  177. function showMain() {
  178. if (sessionStorage.getItem('authToken') === null) {
  179. $('.basic').show();
  180. $('.navbar-anonymous').show();
  181. } else {
  182. $('.navbar-dashboard').show();
  183. }
  184. }
  185.  
  186. function allListings(type) {
  187. hideAll();
  188. $('.other-pets-list').empty();
  189. if (type) {
  190. $.ajax({
  191. method: "GET",
  192. url: kinveyBaseUrl + "appdata/" + kinveyAppKey + `/pets?query={"category":"${type}"}&sort={\"likes\": -1}`,
  193. headers: getKinveyUserAuthHeaders()
  194. }).then((res) => {
  195. res.sort((x, y) => parseInt(y.likes, 10) - parseInt(x.likes, 10));
  196. for (let item of res) {
  197. if (sessionStorage.getItem('userId') !== item._acl.creator) {
  198. const listing = $(`<li class="otherPet">
  199. <h3>Name: ${item.name}</h3>
  200. <p>Category: ${item.category}</p>
  201. <p class="img"><img src="${item.imageURL}"></p>
  202. <p class="description">${item.description}</p></li>`);
  203.  
  204. const wrapper = $('<div class="pet-info"></div>');
  205.  
  206. wrapper.append($('<a href="#"><button class="button"><i class="fas fa-heart"></i> Pet</button></a>')
  207. .on('click', () => pet(item, "dashboard", type)));
  208. wrapper
  209. .append($('<a href="#"><button class="button">Details</button></a>')
  210. .on('click', () => listingDetails(item, "details")));
  211. wrapper.append($(`<i class="fas fa-heart"></i> <span>${item.likes}</span>`));
  212.  
  213. $(listing).append(wrapper);
  214. listing.appendTo($('.other-pets-list'));
  215. }
  216. }
  217. $('.dashboard').show();
  218. }).catch(handleAjaxError);
  219. } else {
  220. $.ajax({
  221. method: "GET",
  222. url: kinveyBaseUrl + "appdata/" + kinveyAppKey + `/pets?query={}&sort={\"likes\": -1}`,
  223. headers: getKinveyUserAuthHeaders()
  224. }).then((res) => {
  225. res.sort((x, y) => parseInt(y.likes, 10) - parseInt(x.likes, 10));
  226. for (let item of res) {
  227. if (sessionStorage.getItem('userId') !== item._acl.creator) {
  228. const listing = $(`<li class="otherPet">
  229. <h3>Name: ${item.name}</h3>
  230. <p>Category: ${item.category}</p>
  231. <p class="img"><img src="${item.imageURL}"></p>
  232. <p class="description">${item.description}</p></li>`);
  233.  
  234. const wrapper = $('<div class="pet-info"></div>');
  235.  
  236. wrapper.append($('<a href="#"><button class="button"><i class="fas fa-heart"></i> Pet</button></a>')
  237. .on('click', () => pet(item, "dashboard", type)));
  238. wrapper
  239. .append($('<a href="#"><button class="button">Details</button></a>')
  240. .on('click', () => listingDetails(item, "details")));
  241. wrapper.append($(`<i class="fas fa-heart"></i> <span>${item.likes}</span>`));
  242.  
  243. $(listing).append(wrapper);
  244. listing.appendTo($('.other-pets-list'));
  245. }
  246. }
  247. $('.dashboard').show();
  248. }).catch(handleAjaxError);
  249. }
  250. }
  251.  
  252. function createListingView() {
  253. hideAll();
  254. $('.create').show();
  255. }
  256.  
  257. function createListing() {
  258. const name = $('.create input[name="name"]').val();
  259. const description = $('.create textarea[name="description"]').val();
  260. const imageURL = $('.create input[name="imageURL"]').val();
  261. const category = $('.create select').find(":selected").text();
  262.  
  263. $.ajax({
  264. method: "POST",
  265. data: {
  266. name, description, imageURL, category, likes: 0
  267. },
  268. headers: getKinveyUserAuthHeaders(),
  269. url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/pets"
  270. }).then(function (res) {
  271. showInfo('Pet created.');
  272. allListings();
  273. $('.create form').trigger('reset');
  274. }).catch(handleAjaxError);
  275. }
  276.  
  277. function editListing(item) {
  278. const description = $('.detailsMyPet textarea').val();
  279.  
  280. $.ajax({
  281. method: "PUT",
  282. url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/pets/" + item._id,
  283. headers: getKinveyUserAuthHeaders(),
  284. data: {
  285. name: item.name, description, imageURL: item.imageURL,
  286. category: item.category, likes: item.likes
  287. },
  288. }).then(function (res) {
  289. showInfo(`Updated successfully!`);
  290. allListings()
  291. }).catch(handleAjaxError);
  292. }
  293.  
  294.  
  295. function deleteListingView(item) {
  296. hideAll();
  297. let section = $('.deletePet');
  298. section.empty();
  299.  
  300. section.append(`<h3>${item.name}</h3>
  301. <p>Pet counter: <i class="fas fa-heart"></i>${item.likes}</p>
  302. <p class="img"><img src="${item.imageURL}"></p>`);
  303.  
  304. let form = $(`<form action="#" method="POST">
  305. <p class="description">${item.description}</p>
  306. </form>`);
  307. form.append($(`<button class="button">Delete</button>`)
  308. .on('click', () => deleteListing(item)));
  309. form.submit(function (event) {
  310. event.preventDefault()
  311. });
  312. section.append(form);
  313. section.show();
  314. }
  315.  
  316. function deleteListing(item) {
  317. $.ajax({
  318. method: "DELETE",
  319. url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/pets/" + item._id,
  320. headers: getKinveyUserAuthHeaders()
  321. }).then(function (res) {
  322. allListings();
  323. showInfo('Pet removed successfully!');
  324. }).catch(handleAjaxError);
  325. }
  326.  
  327. function myListings() {
  328. hideAll();
  329. let user_id = sessionStorage.getItem('userId');
  330. $('.my-pets-list').empty();
  331. $.ajax({
  332. method: "GET",
  333. url: kinveyBaseUrl + "appdata/" + kinveyAppKey + `/pets?query={"_acl.creator":"${user_id}"}`,
  334. headers: getKinveyUserAuthHeaders()
  335. }).then((res) => {
  336. for (let item of res) {
  337. const listing = $(`<li class="myPet">
  338. <h3>Name: ${item.name}</h3>
  339. <p>Category: ${item.category}</p>
  340. <p class="img"><img src="${item.imageURL}"></p>
  341. <p class="description">${item.description}</p></li>`);
  342.  
  343. const wrapper = $('<div class="pet-info"></div>');
  344.  
  345. wrapper.append($(`<a href="#">
  346. </a>`)
  347. .on('click', () => deleteListingView(item)).append(`<button class="button">Delete</button>`));
  348. wrapper.append($(`<a href="#">
  349.  
  350. </a>`)
  351. .on('click', () => listingDetails(item, "edit")).append(`<button class="button">Edit</button>`));
  352. wrapper.append($(`<i class="fas fa-heart"></i> <span>${item.likes}</span>`));
  353.  
  354. $(listing).append(wrapper);
  355. listing.appendTo($('.my-pets-list'));
  356. }
  357. $('.my-pets').show();
  358. $('.my-pets .myPet').show();
  359. }).catch(handleAjaxError);
  360. }
  361.  
  362. function listingDetails(item, type) {
  363. hideAll();
  364. if (type === "details") {
  365. let section = $('.detailsOtherPet');
  366. section.empty();
  367. section.append(`<h3>${item.name}</h3>`);
  368. let p = $(`<p>Pet counter: ${item.likes} </p>`);
  369. p.append($(`<a href="#">
  370. <button class="button"><i class="fas fa-heart"></i>
  371. Pet
  372. </button></a>`).on('click', () => pet(item, "details")));
  373. section.append(p);
  374. section.append($(`<p class="img"><img src="${item.imageURL}"></p>
  375. <p class="description">${item.description}</p>`));
  376. section.show();
  377. } else {
  378. let section = $('.detailsMyPet');
  379. section.empty();
  380. section.append(`<h3>${item.name}</h3>
  381. <p>Pet counter: <i class="fas fa-heart"></i> ${item.likes}</p>
  382. <p class="img"><img src="${item.imageURL}">
  383. </p>`);
  384. let form = $(`<form action="#" method="POST">
  385. <textarea type="text" name="description">${item.description}</textarea>
  386. </form>`);
  387. form.append($(`<button class="button"> Save</button>`).on('click', () => editListing(item)));
  388. form.submit(function (event) {
  389. event.preventDefault()
  390. });
  391. section.append(form);
  392. section.show();
  393. }
  394. }
  395.  
  396. function pet(item, place, type) {
  397. $.ajax({
  398. method: "PUT",
  399. url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/pets/" + item._id,
  400. headers: getKinveyUserAuthHeaders(),
  401. data: {
  402. name: item.name, description: item.description, imageURL: item.imageURL,
  403. category: item.category, likes: +item.likes + 1
  404. },
  405. }).then(function (res) {
  406. if (place === "dashboard") {
  407. allListings(type);
  408. } else {
  409. listingDetails(res, "details");
  410. }
  411. }).catch(handleAjaxError);
  412. }
  413. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement