Act

apify/example-counter

  • Builds
  • latest 0.0.21 / 2017-10-26
  • Created 2017-10-26
  • Last modified 2017-10-26
  • grade 2

Description

This act simply counts from one up. In each run it prints one number. Its state (counter position) is stored in named key-value store. Name of the store is example-counter and you can find in Apify app under the Storages.


API

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

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

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


Example input

Content type: application/json; charset=utf-8

{ "hello": 123 }

Source code

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

const Apify = require('apify');

Apify.main(async () => {
    const keyValueStores = Apify.client.keyValueStores;
    
    // Get store with name 'example-counter'.
    const store = await keyValueStores.getOrCreateStore({ 
        storeName: 'example-counter',
    });
    
    // Get counter state record from store.
    const record = await keyValueStores.getRecord({ 
        key: 'counter',
        storeId: store.id,
    });
    
    // If there is no such record then start from zero.
    let counter = record ? record.body : 0;

    // Increase counter, print and set as output.
    counter ++;
    console.log(`Counter: ${counter}`);
    Apify.setValue('OUTPUT', counter);
    
    // Save increased value back to store.
    await keyValueStores.putRecord({
        storeId: store.id,
        key: 'counter',
        body: counter.toString(), // Record body must be a string or buffer!
    });
});