Advertisement
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. function successGet(data){
  213. data = data.filter(x => x.UserId == userId && x.ProductId == id);
  214.  
  215. if(data){
  216.  
  217. data[0].Quantity = Number(data[0].Quantity) + 1;
  218.  
  219. $.ajax({
  220. method: "PUT",
  221. url: cartUrl,
  222. headers: getKinveyUserAuthHeaders(),
  223. body: JSON.stringify(data[0])
  224. });
  225.  
  226. } else {
  227. let productData = {
  228. UserId: sessionStorage.getItem('userId'),
  229. ProductId: id,
  230. Quantity: 1
  231. };
  232.  
  233. $.ajax({
  234. method: "POST",
  235. url: cartUrl,
  236. data: productData,
  237. headers: getKinveyUserAuthHeaders(),
  238. success: purchaseSuccess,
  239. error: handleAjaxError
  240. });
  241. }
  242. }
  243.  
  244. function purchaseSuccess(){
  245. showInfo('Product purchased.');
  246. }
  247.  
  248. }
  249.  
  250. function loginUser(newUser) {
  251. newUser.preventDefault();
  252. let userData = {
  253. username: $('#loginUsername').val(),
  254. password: $('#loginPasswd').val()
  255. };
  256.  
  257. $.ajax({
  258. method: "POST",
  259. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  260. headers: kinveyAppAuthHeaders,
  261. data: userData,
  262. success: loginSuccess,
  263. error: handleAjaxError
  264. });
  265.  
  266. function loginSuccess(userInfo) {
  267. saveAuthInSession(userInfo);
  268. showHideMenuLinks();
  269. $('#spanMenuLoggedInUser').text("Welcome, " + sessionStorage.getItem('name') + '!');
  270. showUserHomeView();
  271. showInfo('Login successful.');
  272. }
  273. }
  274.  
  275. function registerUser(newUser) {
  276. newUser.preventDefault();
  277. let userData = {
  278. username: $('#registerUsername').val(),
  279. password: $('#registerPasswd').val(),
  280. name: $('#registerName').val()
  281. };
  282. $.ajax({
  283. method: "POST",
  284. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
  285. headers: kinveyAppAuthHeaders,
  286. data: userData,
  287. success: registerSuccess,
  288. error: handleAjaxError
  289. });
  290.  
  291. function registerSuccess(userInfo) {
  292. saveAuthInSession(userInfo);
  293. showHideMenuLinks();
  294. showUserHomeView();
  295. showInfo('User registration successful.');
  296. }
  297. }
  298.  
  299. function logoutUser() {
  300. sessionStorage.clear();
  301. $('#spanMenuLoggedInUser').empty();
  302. showHideMenuLinks();
  303. showView('viewAppHome');
  304. showInfo('Logout successful.');
  305. }
  306.  
  307.  
  308. function getKinveyUserAuthHeaders() {
  309. return {
  310. 'Authorization': "Kinvey " +
  311. sessionStorage.getItem('authToken'),
  312. };
  313. }
  314.  
  315. function saveAuthInSession(userInfo) {
  316. let userAuth = userInfo._kmd.authtoken;
  317. sessionStorage.setItem('authToken', userAuth);
  318. let userId = userInfo._id;
  319. sessionStorage.setItem('userId', userId);
  320. let username = userInfo.username;
  321. sessionStorage.setItem('username', username);
  322. let name = userInfo.name;
  323. sessionStorage.setItem('name', name);
  324. $('#loggedInUser').text(
  325. "Welcome, " + username + "!");
  326. }
  327.  
  328. function handleAjaxError(response) {
  329. let errorMsg = JSON.stringify(response);
  330. if (response.readyState === 0)
  331. errorMsg = "Cannot connect due to network error.";
  332. if (response.responseJSON &&
  333. response.responseJSON.description)
  334. errorMsg = response.responseJSON.description;
  335. showError(errorMsg);
  336. }
  337. function showInfo(message) {
  338. $('#infoBox').text(message);
  339. $('#infoBox').show();
  340. setTimeout(function () {
  341. $('#infoBox').fadeOut();
  342. }, 2000);
  343. }
  344. function showError(errorMsg) {
  345. $('#errorBox').text("Error: " + errorMsg);
  346. $('#errorBox').show();
  347. setTimeout(function () {
  348. $('#errorBox').fadeOut();
  349. }, 2000);
  350. }
  351.  
  352. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement