Guest User

Untitled

a guest
Dec 21st, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.16 KB | None | 0 0
  1. /**
  2. * Created by Merrie on 12/20/16.
  3. */
  4. function startApp() {
  5. const kinveyBaseUrl = "https://baas.kinvey.com/";
  6. const kinveyAppKey = "kid_BkgrHyPNx";
  7. const kinveyAppSecret = "0a80d7870a094292ab4f8e89484ccf62";
  8. const kinveyAppAuthHeaders = {
  9. 'Authorization': "Basic " + btoa(kinveyAppKey + ":" + kinveyAppSecret),
  10. };
  11.  
  12. //Hide status boxes
  13. $('#infoBox').hide();
  14. $('#errorBox').hide();
  15. $('#loadingBox').hide();
  16.  
  17. sessionStorage.clear(); // Clear user auth data
  18.  
  19. showHideMenuLinks();
  20.  
  21. if(sessionStorage.getItem('authToken')) {
  22. $('#spanMenuLoggedInUser').text('Welcome, ' + sessionStorage.getItem('name') + '!');
  23. showUserHomeView()
  24. }else {
  25. $('#spanMenuLoggedInUser').empty();
  26. showAppHomeView();
  27. }
  28.  
  29. //Bind menu links with views
  30. $("#linkMenuAppHome").click(showAppHomeView);
  31. $("#linkMenuLogin").click(showLoginView);
  32. $("#linkMenuRegister").click(showRegisterView);
  33.  
  34. $("#linkMenuUserHome").click(showUserHomeView);
  35. $("#linkMenuShop").click(showShopView);
  36. $("#linkMenuCart").click(showCartView);
  37. $("#linkMenuLogout").click(logoutUser);
  38.  
  39. // Bind the form submit buttons
  40. $(`#formLogin input[type="submit"]`).click(loginUser);
  41. $(`#formRegister input[type="submit"]`).click(registerUser);
  42.  
  43.  
  44. $("#infoBox, #errorBox").click(function () {
  45. $(this).fadeOut();
  46. });
  47.  
  48. // Attach AJAX "loading" event listener
  49. $(document).on({
  50. ajaxStart: function () {
  51. $("#loadingBox").show()
  52. },
  53. ajaxStop: function () {
  54. $("#loadingBox").hide()
  55. }
  56. });
  57.  
  58. function showHideMenuLinks() {
  59. if (sessionStorage.getItem('authToken')) {
  60. // We have logged in user
  61. $("#linkMenuAppHome").hide();
  62. $("#linkMenuLogin").hide();
  63. $("#linkMenuRegister").hide();
  64. $("#linkMenuUserHome").show();
  65. $("#linkMenuShop").show();
  66. $("#linkMenuCart").show();
  67. $("#linkMenuLogout").show();
  68. } else {
  69. // No logged in user
  70. $("#linkMenuAppHome").show();
  71. $("#linkMenuLogin").show();
  72. $("#linkMenuRegister").show();
  73. $("#linkMenuUserHome").hide();
  74. $("#linkMenuShop").hide();
  75. $("#linkMenuCart").hide();
  76. $("#linkMenuLogout").hide();
  77. }
  78. }
  79.  
  80. function showView(viewName) {
  81. // Hide all views and show the selected view only
  82. $('main > section').hide();
  83. $('#' + viewName).show();
  84. }
  85.  
  86. function showAppHomeView() {
  87. //Bind the user home buttons
  88. $("#linkUserHomeShop").click(showShopView);
  89. $("#linkUserHomeCart").click(showCartView);
  90. showView('viewAppHome');
  91. }
  92.  
  93. function showUserHomeView() {
  94. $('#viewUserHomeHeading').text('Welcome, ' + sessionStorage.getItem('name') + '!');
  95. showView('viewUserHome');
  96. }
  97.  
  98. function showLoginView() {
  99. showView('viewLogin');
  100. $('#formLogin').trigger('reset');
  101. }
  102.  
  103. function showRegisterView() {
  104. $('#formRegister').trigger('reset');
  105. showView('viewRegister');
  106. }
  107.  
  108. function showShopView() {
  109. $('#viewShop').empty();
  110. const getShopUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/products`;
  111. let table = $('<table>').append(
  112. `<thead>
  113. <tr>
  114. <th>Product</th>
  115. <th>Description</th>
  116. <th>Price</th>
  117. <th>Actions</th>
  118. </tr>
  119. </thead>`);
  120. $.ajax({
  121. method: "GET",
  122. url: getShopUrl,
  123. headers: getKinveyUserAuthHeaders(),
  124. success: fillTable,
  125. error: handleAjaxError
  126. });
  127. function fillTable(products) {
  128. if (products.length == 0) {
  129. $('#viewShop').empty();
  130. $('#viewShop').text('No products found.')
  131. }
  132. else {
  133. let tbody = $('<tbody>');
  134. for (let prd of products) {
  135. let prcBtn = $('<button>').text("Purchase");
  136. prcBtn.click(x => purchaseProduct(prd._id));
  137. tbody.append($('<tr>')
  138. .append($(`<td>`).text(prd.name))
  139. .append($(`<td>`).text(prd.description))
  140. .append($(`<td>`).text(prd.price.toFixed(2)))
  141. .append($('<td>').append(prcBtn)));
  142. }
  143.  
  144. table.append(tbody);
  145. $('#viewShop').empty();
  146. $('#viewShop').append(table);
  147. }
  148. }
  149. showView('viewShop');
  150. }
  151.  
  152. function showCartView() {
  153. $('#viewCart').empty();
  154. const getCartUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/shoppingCart`;
  155. let table = $('<table>').append(
  156. `<thead>
  157. <tr>
  158. <th>Product</th>
  159. <th>Description</th>
  160. <th>Quantity</th>
  161. <th>Total Price</th>
  162. <th>Actions</th>
  163. </tr>
  164. </thead>`);
  165. $.ajax({
  166. method: "GET",
  167. url: getCartUrl,
  168. headers: getKinveyUserAuthHeaders(),
  169. success: fillTable,
  170. error: handleAjaxError
  171. });
  172. function fillTable(products) {
  173. if (products.length == 0) {
  174. $('#viewCart').empty();
  175. $('#viewCart').text('No products found.')
  176. }
  177. else {
  178. let tbody = $('<tbody>');
  179. for (let prd of products) {
  180. let prcBtn = $('<button>').text("Discard");
  181. prcBtn.click(x => discardProduct(prd._id));
  182. tbody.append($('<tr>')
  183. .append($(`<td>`).text(prd.name))
  184. .append($(`<td>`).text(prd.description))
  185. .append($('<td>').text(prd.quantity))
  186. .append($(`<td>`).text(prd.totalPrice.toFixed(2)))
  187. .append($('<td>').append(prcBtn)));
  188. }
  189.  
  190. table.append(tbody);
  191. $('#viewCart').empty();
  192. $('#viewCart').append(table);
  193. }
  194. }
  195. showView('viewCart');
  196. }
  197.  
  198. function purchaseProduct(id) {
  199.  
  200.  
  201. let cartUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/shoppingCart";
  202.  
  203. $.ajax({
  204. method: "GET",
  205. url: cartUrl,
  206. headers: getKinveyUserAuthHeaders(),
  207. success: successGet,
  208. error: handleAjaxError
  209.  
  210. });
  211.  
  212. let result = result.filter(x => x.userId == userId && x.productId == id);
  213.  
  214. if(result){
  215.  
  216. result.quantity = Number(result.quantity) + 1;
  217.  
  218. $.ajax({
  219. method: "PUT",
  220. url: cartUrl,
  221. headers: getKinveyUserAuthHeaders(),
  222. body: {
  223. Quantity: JSON.stringify(result),
  224. }
  225. });
  226.  
  227. } else {
  228. let productData = {
  229. UserId: sessionStorage.getItem('userId'),
  230. ProductId: id,
  231. Quantity: 1
  232. };
  233.  
  234. $.ajax({
  235. method: "POST",
  236. url: cartUrl,
  237. data: productData,
  238. headers: getKinveyUserAuthHeaders(),
  239. success: purchaseSuccess,
  240. error: handleAjaxError
  241. });
  242. }
  243.  
  244. function successGet(){
  245. console.log("Got the whole cart");
  246. }
  247.  
  248. function purchaseSuccess(){
  249. showInfo('Product purchased.');
  250. }
  251.  
  252. }
  253.  
  254. function loginUser(newUser) {
  255. newUser.preventDefault();
  256. let userData = {
  257. username: $('#loginUsername').val(),
  258. password: $('#loginPasswd').val()
  259. };
  260.  
  261. $.ajax({
  262. method: "POST",
  263. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  264. headers: kinveyAppAuthHeaders,
  265. data: userData,
  266. success: loginSuccess,
  267. error: handleAjaxError
  268. });
  269.  
  270. function loginSuccess(userInfo) {
  271. saveAuthInSession(userInfo);
  272. showHideMenuLinks();
  273. $('#spanMenuLoggedInUser').text("Welcome, " + sessionStorage.getItem('name') + '!');
  274. showUserHomeView();
  275. showInfo('Login successful.');
  276. }
  277. }
  278. function registerUser(newUser) {
  279. newUser.preventDefault();
  280. let userData = {
  281. username: $('#registerUsername').val(),
  282. password: $('#registerPasswd').val(),
  283. name: $('#registerName').val()
  284. };
  285. $.ajax({
  286. method: "POST",
  287. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
  288. headers: kinveyAppAuthHeaders,
  289. data: userData,
  290. success: registerSuccess,
  291. error: handleAjaxError
  292. });
  293.  
  294. function registerSuccess(userInfo) {
  295. saveAuthInSession(userInfo);
  296. showHideMenuLinks();
  297. showUserHomeView();
  298. showInfo('User registration successful.');
  299. }
  300. }
  301.  
  302. function logoutUser() {
  303. sessionStorage.clear();
  304. $('#spanMenuLoggedInUser').empty();
  305. showHideMenuLinks();
  306. showView('viewAppHome');
  307. showInfo('Logout successful.');
  308. }
  309.  
  310.  
  311. function getKinveyUserAuthHeaders() {
  312. return {
  313. 'Authorization': "Kinvey " +
  314. sessionStorage.getItem('authToken'),
  315. };
  316. }
  317.  
  318. function saveAuthInSession(userInfo) {
  319. let userAuth = userInfo._kmd.authtoken;
  320. sessionStorage.setItem('authToken', userAuth);
  321. let userId = userInfo._id;
  322. sessionStorage.setItem('userId', userId);
  323. let username = userInfo.username;
  324. sessionStorage.setItem('username', username);
  325. let name = userInfo.name;
  326. sessionStorage.setItem('name', name);
  327. $('#loggedInUser').text(
  328. "Welcome, " + username + "!");
  329. }
  330.  
  331. function handleAjaxError(response) {
  332. let errorMsg = JSON.stringify(response);
  333. if (response.readyState === 0)
  334. errorMsg = "Cannot connect due to network error.";
  335. if (response.responseJSON &&
  336. response.responseJSON.description)
  337. errorMsg = response.responseJSON.description;
  338. showError(errorMsg);
  339. }
  340. function showInfo(message) {
  341. $('#infoBox').text(message);
  342. $('#infoBox').show();
  343. setTimeout(function () {
  344. $('#infoBox').fadeOut();
  345. }, 2000);
  346. }
  347. function showError(errorMsg) {
  348. $('#errorBox').text("Error: " + errorMsg);
  349. $('#errorBox').show();
  350. setTimeout(function () {
  351. $('#errorBox').fadeOut();
  352. }, 2000);
  353. }
  354.  
  355. }
Advertisement
Add Comment
Please, Sign In to add comment