1const Apify = require('apify');
2
3const { log } = console;
4
5Apify.main(async () => {
6 const input = await Apify.getValue('INPUT');
7
8 const { client } = Apify;
9 const { keyValueStores } = client;
10 const {
11 count, limit, actName, email
12 } = input;
13 if (!count || !limit || !actName || !email) {
14 throw new Error('Missing input value.');
15 }
16 const { id: storeId } = await keyValueStores.getOrCreateStore({
17 storeName: actName
18 });
19 client.setOptions({ storeId });
20
21 const record = await keyValueStores.getRecord({ key: 'STATE' });
22
23 const storeRecord = record && record.body ? record.body : {};
24
25 const previousState = typeof storeRecord === 'string' ?
26 JSON.parse(storeRecord) : storeRecord;
27 log('Previous STATE:', previousState);
28
29 const currentCount = Number(count) || 0;
30 const previousCount = Number(previousState.count) || 0;
31 const nextCount = previousCount + currentCount;
32
33 if (nextCount > Number(limit)) {
34 const text = `
35 The ${actName} has reached its current page visits limit.
36
37 Current limit: ${limit},
38 Current count: ${nextCount}
39
40 Please notify the user to updgrade its current plan!
41 `;
42 log('Sending notification email...');
43 await Apify.call('apify/send-mail', {
44 to: email,
45 subject: `The ${actName} act has reached its limit!`,
46 text
47 });
48 }
49
50 const nextState = Object.assign({}, { count: nextCount, limit });
51 log('Next STATE:', nextState);
52
53 await keyValueStores.putRecord({
54 key: 'STATE',
55 body: JSON.stringify(nextState)
56 });
57});