Actor

juansgaitan/counter

  • Builds
  • latest 0.1.1 / 2018-03-06
  • Created 2018-03-06
  • Last modified 2018-03-06
  • grade 1

Description

Counts the current page visits inside an act.


API

To run the actor, send a HTTP POST request to:

https://api.apify.com/v2/acts/juansgaitan~counter/runs?token=<YOUR_API_TOKEN>

The POST payload will be passed as input for the actor. For more information, read the docs.


Example input

Content type: application/json

{
    "count": "100",
    "email": "juan@apify.com",
    "limit": "155",
    "actName": "Name-of-the-act"
}

Source code

Based on the apify/actor-node-basic Docker image (see docs).

const Apify = require('apify');

const { log } = console;

Apify.main(async () => {
  const input = await Apify.getValue('INPUT');

  const { client } = Apify;
  const { keyValueStores } = client;
  const {
    count, limit, actName, email
  } = input;
  if (!count || !limit || !actName || !email) {
    throw new Error('Missing input value.');
  }
  const { id: storeId } = await keyValueStores.getOrCreateStore({
    storeName: actName
  });
  client.setOptions({ storeId });

  const record = await keyValueStores.getRecord({ key: 'STATE' });

  const storeRecord = record && record.body ? record.body : {};

  const previousState = typeof storeRecord === 'string' ?
    JSON.parse(storeRecord) : storeRecord;
  log('Previous STATE:', previousState);

  const currentCount = Number(count) || 0;
  const previousCount = Number(previousState.count) || 0;
  const nextCount = previousCount + currentCount;

  if (nextCount > Number(limit)) {
    const text = `
      The ${actName} has reached its current page visits limit.

      Current limit: ${limit},
      Current count: ${nextCount}

      Please notify the user to updgrade its current plan!
    `;
    log('Sending notification email...');
    await Apify.call('apify/send-mail', {
      to: email,
      subject: `The ${actName} act has reached its limit!`,
      text
    });
  }

  const nextState = Object.assign({}, { count: nextCount, limit });
  log('Next STATE:', nextState);

  await keyValueStores.putRecord({
    key: 'STATE',
    body: JSON.stringify(nextState)
  });
});