PUBLICREADY
mainController.js
const bluebird = require('bluebird')
const moment = require('moment')
const CoinMarketCap = require('coinmarketcap-api')
const apiKey = '6e3770bc-c2df-4771-86da-f68ee70e3df2'
const client = new CoinMarketCap(apiKey)
const cacheHelper = require('./utils/cacheHelper')
const coinParser = require('./utils/coinParser')
const cacheKey = 'coins'
const mainController = (() => {
  const renderHomePage = (res, cachedData) => {
    res.render('homepage', {
      timeOfUpdate: cachedData.timeOfUpdate.fromNow(),
      coins: cachedData.coins,
      totalMarketCap: cachedData.totalMarketCap
    })
  }
  const getCoins = (req, res) => {
    if (!cacheHelper.isEmpty(cacheKey)) {
      console.log('Cache not empty, returning value')
      const cachedData = cacheHelper.getValue(cacheKey)
      renderHomePage(res, cachedData)
    } else {
      console.log('Cache is empty, fetching data')
      bluebird.all([
        client.getTickers(),
        client.getGlobal()
      ])
        .spread((responseFromRequest1, responseFromRequest2) => {
          console.log('Fetched coins and total market cap')
          const parsedCoins = coinParser.parseCoins(responseFromRequest1)
          const parsedTotalMarketCap = coinParser.parseTotalMarketCap(responseFromRequest2)
          const dataToCache = {
            timeOfUpdate: moment(),
            coins: parsedCoins,
            totalMarketCap: parsedTotalMarketCap
          }
          cacheHelper.setValue(cacheKey, dataToCache)
          console.log('Successfully cached data')
          renderHomePage(res, dataToCache)
        })
        .catch(err => {
          console.error('Error:', err)
          res.status(500)
        })
    }
  }
  return {
    getCoins
  }
})()
module.exports = mainController