Advertisement
Guest User

Untitled

a guest
Nov 29th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.87 KB | None | 0 0
  1. function startApp() {
  2. sessionStorage.clear();
  3.  
  4. showHideMenuLinks();
  5. showView('viewHome');
  6.  
  7. const kinveyBaseUrl = "https://baas.kinvey.com/";
  8. const kinveyAppKey = "kid_HkihhHmGx";
  9. const kinveyAppSecret = "81c7d8d9158b4c0bb53027bf1074186e";
  10. const kinveyAppAuthHeaders = {
  11. 'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
  12. };
  13.  
  14. $("#linkHome").click(showHomeView);
  15. $("#linkLogin").click(showLoginView);
  16. $("#linkRegister").click(showRegisterView);
  17. $("#linkListAds").click(listAds);
  18. $("#linkCreateAd").click(showCreateAdView);
  19. $("#linkLogout").click(logoutUser);
  20.  
  21. $("#buttonLoginUser").click(loginUser);
  22. $("#buttonRegisterUser").click(registerUser);
  23. $("#buttonCreateAd").click(createAd);
  24. $("#buttonEditAd").click(editAd);
  25.  
  26. $("#infoBox, #errorBox").click(function() {
  27. $(this).fadeOut();
  28. });
  29.  
  30. function showView(viewName) {
  31. $('main > section').hide();
  32. $('#' + viewName).show();
  33. }
  34.  
  35. function showHomeView() {
  36. showView('viewHome');
  37. }
  38.  
  39. function showLoginView() {
  40. showView('viewLogin');
  41. $('#formLogin').trigger('reset');
  42. }
  43.  
  44. function showRegisterView() {
  45. $('#formRegister').trigger('reset');
  46. showView('viewRegister');
  47. }
  48.  
  49. function showCreateAdView() {
  50. $('#formCreateAd').trigger('reset');
  51. showView('viewCreateAd');
  52. }
  53.  
  54. function showHideMenuLinks() {
  55. $("#linkHome").show();
  56. if (sessionStorage.getItem('authToken') == null) {
  57. $("#linkLogin").show();
  58. $("#linkRegister").show();
  59. $("#linkListAds").hide();
  60. $("#linkCreateAd").hide();
  61. $("#linkLogout").hide();
  62. } else {
  63. $("#linkLogin").hide();
  64. $("#linkRegister").hide();
  65. $("#linkListAds").show();
  66. $("#linkCreateAd").show();
  67. $("#linkLogout").show();
  68. }
  69. }
  70.  
  71. function registerUser() {
  72. const kinveyRegisterUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/";
  73. let userData = {
  74. username: $('#formRegister input[name=username]').val(),
  75. password: $('#formRegister input[name=passwd]').val()
  76. };
  77. $.ajax({
  78. method: "POST",
  79. url: kinveyRegisterUrl,
  80. headers: kinveyAppAuthHeaders,
  81. data: userData,
  82. success: registerSuccess,
  83. error: handleAjaxError
  84. });
  85.  
  86. function registerSuccess(userInfo) {
  87. saveAuthInSession(userInfo);
  88. showHideMenuLinks();
  89. listAds();
  90. showInfo('User registration successful.');
  91. }
  92. }
  93.  
  94. function loginUser() {
  95. const kinveyLoginUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/login";
  96. let userData = {
  97. username: $('#formLogin input[name=username]').val(),
  98. password: $('#formLogin input[name=passwd]').val()
  99. };
  100. $.ajax({
  101. method: "POST",
  102. url: kinveyLoginUrl,
  103. headers: kinveyAppAuthHeaders,
  104. data: userData,
  105. success: loginSuccess,
  106. error: handleAjaxError
  107. });
  108.  
  109. function loginSuccess(userInfo) {
  110. saveAuthInSession(userInfo);
  111. showHideMenuLinks();
  112. listAds();
  113. showInfo('Login successful.');
  114. }
  115. }
  116.  
  117. function createAd() {
  118. const kinveyBooksUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/ads";
  119. let bookData = {
  120. publisher: sessionStorage['userId'],
  121. title: $('#formCreateAd input[name=title]').val(),
  122. description: $('#formCreateAd textarea[name=description]').val(),
  123. datePublished: $('#formCreateAd input[name=datePublished]').val(),
  124. price: $('#formCreateAd input[name=price]').val()
  125. };
  126.  
  127. $.ajax({
  128. method: "POST",
  129. url: kinveyBooksUrl,
  130. headers: getKinveyUserAuthHeaders(),
  131. data: bookData,
  132. success: createAdSuccess,
  133. error: handleAjaxError
  134. });
  135.  
  136. function createAdSuccess(response) {
  137. listAds();
  138. showInfo('Book created.');
  139. }
  140. }
  141.  
  142. function editAd() {
  143. const kinveyBookUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey +
  144. "/ads/" + $('#formEditBook input[name=id]').val();
  145. let bookData = {
  146. title: $('#formEditAd input[name=title]').val().trim(),
  147. description: $('#formEditAd textarea[name=description]').val().trim(),
  148. datePublished: $('#formEditAd input[name=datePublished]').val(),
  149. price: $('#formEditAd input[name=price]').val()
  150. };
  151. $.ajax({
  152. method: "PUT",
  153. url: kinveyBookUrl,
  154. headers: getKinveyUserAuthHeaders(),
  155. data: bookData,
  156. success: editAdSuccess,
  157. error: handleAjaxError
  158. });
  159.  
  160. function editAdSuccess(response) {
  161. listAds();
  162. showInfo('Ad edited.');
  163. }
  164. }
  165.  
  166. function listAds() {
  167. $('#ads').empty();
  168. showView('viewAds');
  169.  
  170. const kinveyBooksUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/ads";
  171. $.ajax({
  172. method: "GET",
  173. url: kinveyBooksUrl,
  174. headers: getKinveyUserAuthHeaders(),
  175. success: loadAdsSuccess,
  176. error: handleAjaxError
  177. });
  178.  
  179. function loadAdsSuccess(ads) {
  180. showInfo('Ads loaded.');
  181. if (ads.length == 0) {
  182. $('#ads').text('No ads.');
  183. } else {
  184. let adsTable = $('<table>')
  185. .append($('<tr>').append(
  186. '<th>Title</th>',
  187. '<th>Publisher</th>',
  188. '<th>Description</th>',
  189. '<th>Price</th>',
  190. '<th>Date Published</th>')
  191. );
  192. for (let ad of ads) {
  193. let links = [];
  194. if (ad._acl.creator == sessionStorage['userId']) {
  195. let deleteLink = $('<a href="#">[Delete]</a>')
  196. .click(function() {
  197. deleteAd(ad)
  198. });
  199. let editLink = $('<a href="#">[Edit]</a>')
  200. .click(function() {
  201. loadAdForEdit(ad)
  202. });
  203. links = [deleteLink, ' ', editLink];
  204. }
  205. adsTable.append($('<tr>').append(
  206. $('<td>').text(ad.title),
  207. $('<td>').text(sessionStorage['userId']),
  208. $('<td>').text(ad.description),
  209. $('<td>').text(ad.price),
  210. $('<td>').text(ad.datePublished),
  211. $('<td>').append(links)
  212. ));
  213. }
  214. $('#ads').append(adsTable);
  215. }
  216. }
  217. }
  218.  
  219. function deleteAd(ad) {
  220. const kinveyBookUrl = kinveyBaseUrl + "appdata/" +
  221. kinveyAppKey + "/ads/" + ad._id;
  222. $.ajax({
  223. method: "DELETE",
  224. url: kinveyBookUrl,
  225. headers: getKinveyUserAuthHeaders(),
  226. success: deleteAdSuccess,
  227. error: handleAjaxError
  228. });
  229.  
  230. function deleteAdSuccess(response) {
  231. listAds();
  232. showInfo('Ad deleted.');
  233. }
  234. }
  235.  
  236. function loadAdForEdit(ad) {
  237. const kinveyBookUrl = kinveyBaseUrl + "appdata/" +
  238. kinveyAppKey + "/ads/" + ad._id;
  239. $.ajax({
  240. method: "GET",
  241. url: kinveyBookUrl,
  242. headers: getKinveyUserAuthHeaders(),
  243. success: loadAdForEditSuccess,
  244. error: handleAjaxError
  245. });
  246.  
  247. function loadAdForEditSuccess(ad) {
  248. $('#formEditAd input[name=id]').val(ad._id);
  249. $('#formEditAd input[name=publisher]').val(ad.publisher);
  250. $('#formEditAd input[name=title]').val(ad.title);
  251. $('#formEditAd textarea[name=description]').val(ad.description);
  252. $('#formEditAd input[name=datePublished]').val(ad.datePublished);
  253. $('#formEditAd input[name=price]').val(ad.price);
  254. showView('viewEditAd');
  255. }
  256. }
  257.  
  258. function saveAuthInSession(userInfo) {
  259. let userAuth = userInfo._kmd.authtoken;
  260. sessionStorage.setItem('authToken', userAuth);
  261. let userId = userInfo._id;
  262. sessionStorage.setItem('userId', userId);
  263. let username = userInfo.username;
  264. $('#loggedInUser').text("Welcome, " + username + "!");
  265. }
  266.  
  267. function getKinveyUserAuthHeaders() {
  268. return {
  269. 'Authorization': "Kinvey " + sessionStorage.getItem('authToken'),
  270. };
  271. }
  272.  
  273. function handleAjaxError(response) {
  274. let errorMsg = JSON.stringify(response);
  275. if (response.readyState === 0)
  276. errorMsg = "Cannot connect due to network error.";
  277. if (response.responseJSON && response.responseJSON.description)
  278. errorMsg = response.responseJSON.description;
  279. showError(errorMsg);
  280. }
  281.  
  282. function showError(errorMsg) {
  283. $('#errorBox').text("Error: " + errorMsg);
  284. $('#errorBox').show();
  285. }
  286.  
  287. function logoutUser() {
  288. sessionStorage.clear();
  289. $('#loggedInUser').text("");
  290. showHideMenuLinks();
  291. showView('viewHome');
  292. showInfo('Logout successful.');
  293. }
  294.  
  295. function showInfo(message) {
  296. $('#infoBox').text(message);
  297. $('#infoBox').show();
  298. setTimeout(function() {
  299. $('#infoBox').fadeOut();
  300. }, 3000);
  301. }
  302. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement