{"size": 1136, "ext": "js", "max_stars_repo_path": "server/jobs/coinUpdater.js", "max_stars_repo_name": "rjschill87/CryptoTracker", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/jobs/coinUpdater.js", "max_issues_repo_name": "rjschill87/CryptoTracker", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/jobs/coinUpdater.js", "max_forks_repo_name": "rjschill87/CryptoTracker", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.72, "max_line_length": 90, "alphanum_fraction": 0.5774647887}
const { CronJob } = require('cron')
const axios = require('axios')
const Coin = require('../models/Coin')

const apiKey = process.env.CMC_API_KEY
const endpoint = process.env.CMC_URL

const updateCoinPrices = (coinObjects) => {
  coinObjects.forEach((coinObj) => {
    const { name, symbol } = coinObj
    const price = coinObj.quote.USD.price.toFixed(2)

    Coin.findOneAndUpdate({ ticker: symbol }, { $set: { name, price } }, { upsert: true })
      .exec((err) => {
        if (err) {
          console.log('>>> err updating coin price', ticker)
        }
      })
  })
}

const fetchCoinPrices = () => {
  const url = `${endpoint}v1/cryptocurrency/listings/latest?limit=5000`

  axios.get(url, {
    headers: {
      'X-CMC_PRO_API_KEY': apiKey
    }
  })
  .then((res) => {
    const { data } = res
    updateCoinPrices(data.data)
  })
  .catch((err) => {
    console.log('>>> fetchCoinPrices err', err);
  })
}

module.exports = {
  run: () => {
    const job1 = new CronJob({
      cronTime: '*/7 * * * * *',
      onTick: fetchCoinPrices,
      start: false,
      timeZone: 'America/New_York',
    });

    job1.start();
  }
}