Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.35 KB | None | 0 0
  1. import fetch from 'isomorphic-fetch';
  2. import lodash from 'lodash';
  3. import lockr from 'lockr';
  4.  
  5. import {
  6. BASE_URL,
  7. } from '../constants/Config';
  8.  
  9. export default {
  10. totalTransactions: 0,
  11. transactions: [],
  12.  
  13. /**
  14. * Add transaction
  15. * @param {Object} transaction transaction model from formData
  16. * @return {promise} returns a promise that resolves the updated transactions
  17. */
  18. add(transaction) {
  19. return new Promise((resolve) => {
  20. const transactionModel = {
  21. Amount: transaction.amount,
  22. Company: transaction.company,
  23. Date: transaction.date,
  24. Ledger: transaction.ledger
  25. };
  26.  
  27. // add transaction to transactions set in localstorage
  28. lockr.sadd('transactions', transactionModel);
  29. this.transactions.push(transactionModel);
  30.  
  31. resolve(this.serializeTransactions(this.transactions));
  32. });
  33. },
  34.  
  35. /**
  36. * Fetches a given page
  37. * @param {Integer} page The page to fetch
  38. * @return {Promise} an isomorphic fetch response
  39. */
  40. fetchPage(page) {
  41. return fetch(`${BASE_URL}${page}.json`)
  42. .then((response) => {
  43. if (response.status >= 400) {
  44. throw new Error('Bad response from server');
  45. }
  46.  
  47. return response.json();
  48. });
  49. },
  50.  
  51. /**
  52. * Fetches the first page, calculates the pageCount, and fetches the remaining
  53. * transactions
  54. * @return {Promise} an isomorphic fetch response
  55. */
  56. fetchFirstTransaction() {
  57. return this.fetchPage(1)
  58. .then((response) => {
  59. this.transactions = this.transactions.concat(response.transactions);
  60. this.totalTransactions = response.totalCount;
  61. const pageCount = Math.ceil(this.totalTransactions / this.transactions.length);
  62.  
  63. if (pageCount > 1) {
  64. return this.fetchRemainingTransactions(pageCount);
  65. }
  66.  
  67. this.resolve(this.serializeTransactions(this.transactions));
  68. });
  69. },
  70.  
  71. /**
  72. * Fetches the remaining transactions by build an array of requests and
  73. * resolving them all
  74. * @param {Integer} pageCount the total number of pages
  75. * @return {Promise} a promise that resolves after all requests have been
  76. * fetched
  77. */
  78. fetchRemainingTransactions(pageCount) {
  79. const transactionRequests = lodash.range(2, (pageCount + 1))
  80. .map(transactionRequest => this.fetchPage(transactionRequest));
  81.  
  82. return Promise.all(transactionRequests).then((responses) => {
  83. const remainingTransactions = responses.map(response => response.transactions);
  84.  
  85. this.transactions = this.transactions.concat(lodash.flatten(remainingTransactions));
  86.  
  87. this.resolve(this.serializeTransactions(this.transactions));
  88. });
  89. },
  90.  
  91. /**
  92. * Start the fetch process
  93. * @return {Promise} that resolves serialized transactions
  94. */
  95. fetch() {
  96. this.initializeLocalStorage();
  97. this.fetchFirstTransaction();
  98.  
  99. return new Promise((resolve) => {
  100. this.resolve = resolve;
  101. });
  102. },
  103.  
  104. /**
  105. * Initialize the transaction with the localstorage set with the key
  106. * 'transactions'
  107. * @return {Array} transactions
  108. */
  109. initializeLocalStorage() {
  110. this.transactions = this.transactions.concat(lockr.smembers('transactions'));
  111.  
  112. return this.transactions;
  113. },
  114.  
  115. /**
  116. * Serialize the balance calculation
  117. * @param {Array} transactions without a balance field
  118. * @return {Array} transactions with a balance field
  119. */
  120. serializeTransactionBalance(transactions) {
  121. let balance = 0;
  122.  
  123. return transactions.map(transaction => {
  124. balance += transaction.amount;
  125. transaction.balance = Math.round(balance * 1e2) / 1e2;
  126.  
  127. return transaction;
  128. }).reverse();
  129. },
  130.  
  131. /**
  132. * Map transactions to clean up object key naming and date format
  133. * @return {Array} the serialized list of transactions
  134. */
  135. serializeTransactions() {
  136. let transactions = this.transactions.map((transaction) => {
  137. const transactionDateArray = transaction.Date.split('-');
  138. const transactionDate = new Date(
  139. transactionDateArray[0],
  140. transactionDateArray[1] - 1,
  141. transactionDateArray[2]
  142. );
  143.  
  144. return {
  145. amount: parseFloat(transaction.Amount),
  146. company: transaction.Company,
  147. date: transactionDate,
  148. ledger: transaction.Ledger
  149. };
  150. });
  151.  
  152. transactions = lodash.chain(transactions)
  153. .sortByOrder('date', 'desc')
  154. .reverse()
  155. .value();
  156.  
  157. return this.serializeTransactionBalance(transactions);
  158. }
  159. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement