Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import fetch from 'isomorphic-fetch';
- import lodash from 'lodash';
- import lockr from 'lockr';
- import {
- BASE_URL,
- } from '../constants/Config';
- export default {
- totalTransactions: 0,
- transactions: [],
- /**
- * Add transaction
- * @param {Object} transaction transaction model from formData
- * @return {promise} returns a promise that resolves the updated transactions
- */
- add(transaction) {
- return new Promise((resolve) => {
- const transactionModel = {
- Amount: transaction.amount,
- Company: transaction.company,
- Date: transaction.date,
- Ledger: transaction.ledger
- };
- // add transaction to transactions set in localstorage
- lockr.sadd('transactions', transactionModel);
- this.transactions.push(transactionModel);
- resolve(this.serializeTransactions(this.transactions));
- });
- },
- /**
- * Fetches a given page
- * @param {Integer} page The page to fetch
- * @return {Promise} an isomorphic fetch response
- */
- fetchPage(page) {
- return fetch(`${BASE_URL}${page}.json`)
- .then((response) => {
- if (response.status >= 400) {
- throw new Error('Bad response from server');
- }
- return response.json();
- });
- },
- /**
- * Fetches the first page, calculates the pageCount, and fetches the remaining
- * transactions
- * @return {Promise} an isomorphic fetch response
- */
- fetchFirstTransaction() {
- return this.fetchPage(1)
- .then((response) => {
- this.transactions = this.transactions.concat(response.transactions);
- this.totalTransactions = response.totalCount;
- const pageCount = Math.ceil(this.totalTransactions / this.transactions.length);
- if (pageCount > 1) {
- return this.fetchRemainingTransactions(pageCount);
- }
- this.resolve(this.serializeTransactions(this.transactions));
- });
- },
- /**
- * Fetches the remaining transactions by build an array of requests and
- * resolving them all
- * @param {Integer} pageCount the total number of pages
- * @return {Promise} a promise that resolves after all requests have been
- * fetched
- */
- fetchRemainingTransactions(pageCount) {
- const transactionRequests = lodash.range(2, (pageCount + 1))
- .map(transactionRequest => this.fetchPage(transactionRequest));
- return Promise.all(transactionRequests).then((responses) => {
- const remainingTransactions = responses.map(response => response.transactions);
- this.transactions = this.transactions.concat(lodash.flatten(remainingTransactions));
- this.resolve(this.serializeTransactions(this.transactions));
- });
- },
- /**
- * Start the fetch process
- * @return {Promise} that resolves serialized transactions
- */
- fetch() {
- this.initializeLocalStorage();
- this.fetchFirstTransaction();
- return new Promise((resolve) => {
- this.resolve = resolve;
- });
- },
- /**
- * Initialize the transaction with the localstorage set with the key
- * 'transactions'
- * @return {Array} transactions
- */
- initializeLocalStorage() {
- this.transactions = this.transactions.concat(lockr.smembers('transactions'));
- return this.transactions;
- },
- /**
- * Serialize the balance calculation
- * @param {Array} transactions without a balance field
- * @return {Array} transactions with a balance field
- */
- serializeTransactionBalance(transactions) {
- let balance = 0;
- return transactions.map(transaction => {
- balance += transaction.amount;
- transaction.balance = Math.round(balance * 1e2) / 1e2;
- return transaction;
- }).reverse();
- },
- /**
- * Map transactions to clean up object key naming and date format
- * @return {Array} the serialized list of transactions
- */
- serializeTransactions() {
- let transactions = this.transactions.map((transaction) => {
- const transactionDateArray = transaction.Date.split('-');
- const transactionDate = new Date(
- transactionDateArray[0],
- transactionDateArray[1] - 1,
- transactionDateArray[2]
- );
- return {
- amount: parseFloat(transaction.Amount),
- company: transaction.Company,
- date: transactionDate,
- ledger: transaction.Ledger
- };
- });
- transactions = lodash.chain(transactions)
- .sortByOrder('date', 'desc')
- .reverse()
- .value();
- return this.serializeTransactionBalance(transactions);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement