Now that we got daily visits, let’s switch to get the last 30 days data.

We want to get the total count of the last 30 days.

To start with, we’ll install Moment to handle dates. In the previous lesson we relied on passing Google today and yesterday. Now we need to property handle dates.

Add moment to the package.json.

Import it using

const moment = require('moment')

We need to get dates in the format YYYY-MM-DD, so here’s how we’ll get them:

moment().format('YYYY-MM-DD') //today

To move around in time, we’ll use the add() and subtract() methods:

moment().add(30, 'days')
moment().subtract(30, 'days')

Check my Moment.js tutorial for more info on this library.

Get last 30 days visits

In getData(), we get the dates we are looking for using:

const daysAgo30 = moment().subtract(30, 'days').format('YYYY-MM-DD')
const daysAgo60 = moment().subtract(60, 'days').format('YYYY-MM-DD')

and we add to the monthly property the new data points:

monthly: {
  total: await getDailyData(item.id, '30daysAgo', 'today'),
  improvement_total: await getDailyData(item.id, daysAgo60, daysAgo30),
  organic: await getDailyData(item.id, '30daysAgo', 'today', true),
  improvement_organic: await getDailyData(item.id, daysAgo60, daysAgo30, true)
}

Get the percentage increment over previous 30 days

Once we have the number, getting the percentage increment (or decrement!) is can be done using this formula:

const total_change_percentage = monthly.improvement_total / monthly.total * 100
const organic_change_percentage = monthly.improvement_organic / monthly.organic * 100

The code at this point is available at https://glitch.com/edit/#!/node-course-project-analytics-dashboard-c?path=server.js


Go to the next lesson