Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

3.1 KB
Raw Blame
import {
  createTrigger,
  TriggerStrategy,
  PiecePropValueSchema,
  OAuth2PropertyValue,
  AppConnectionValueForAuthProperty,
  isNil,
} from '@activepieces/pieces-framework';
import {
  DedupeStrategy,
  Polling,
  pollingHelper,
  HttpMethod,
  getAccessTokenOrThrow,
} from '@activepieces/pieces-common';
import { makeRequest } from '../common';
import { pinterestAuth } from '../common/auth';
import { newFollowerTriggerOutputSchema } from '../output-schemas';

const polling: Polling<
  AppConnectionValueForAuthProperty<typeof pinterestAuth>,
  Record<string, any>
> = {
  strategy: DedupeStrategy.LAST_ITEM,
  items: async ({ auth, lastItemId }) => {
    let bookmark: string | undefined = undefined;
    let followers: any[] = [];
    let pageCount = 0;
    const maxPages = 20; // Limit to prevent excessive API calls

    do {
      pageCount++;

      // Build query parameters
      const searchParams = new URLSearchParams();
      if (bookmark) {
        searchParams.append('bookmark', bookmark);
      }

      const queryString = searchParams.toString();
      const path = `/user_account/followers${
        queryString ? `?${queryString}` : ''
      }`;

      try {
        const response = await makeRequest(
          getAccessTokenOrThrow(auth as OAuth2PropertyValue),
          HttpMethod.GET,
          path
        );

        const items = response.items || [];
        followers = followers.concat(items);
        bookmark = response.bookmark;

        // Rate limiting awareness - add delay between requests
        if (bookmark && pageCount < maxPages) {
          await new Promise((resolve) => setTimeout(resolve, 100));
        }
      } catch (error) {
        // Returning a partial read would store the newest follower as lastItem,
        // so next poll finds it on page one and treats the unread rest as seen.
        // isNil, not truthiness: an empty username is still a real checkpoint.
        if (!isNil(lastItemId)) {
          throw error;
        }
        console.error('Error fetching followers:', error);
        break;
      }
    } while (bookmark && pageCount < maxPages);

    // Return items with username as identifier
    return followers.map((item) => ({
      id: item.username,
      data: item,
    }));
  },
};

export const newFollower = createTrigger({
  auth: pinterestAuth,
  name: 'newFollower',
  classification: 'READ',
  outputSchema: newFollowerTriggerOutputSchema,
  displayName: 'New Follower',
  description: 'Triggers when a user gains a new follower.',
  aiMetadata: {
    description:
      "Fires when the authenticated Pinterest account gains a new follower, emitting the follower's account info. Polls the account's followers list and emits entries not seen before.",
  },
  props: {},
  sampleData: {
    username: 'sample_username',
    type: 'user',
  },
  type: TriggerStrategy.POLLING,
  async test(context) {
    return await pollingHelper.test(polling, context);
  },
  async onEnable(context) {
    await pollingHelper.onEnable(polling, context);
  },
  async onDisable(context) {
    await pollingHelper.onDisable(polling, context);
  },
  async run(context) {
    return await pollingHelper.poll(polling, context);
  },
});