sources/new-unfollower-of-user/new-unfollower-of-user.mjs
import { defineSource } from "@pipedream/types"; import common from "../common/base.mjs"; import { getUserSummary as getItemSummary } from "../common/getItemSummary.mjs"; import { DOCS_LINK, MAX_RESULTS_PER_PAGE, } from "../../actions/list-followers/list-followers.mjs"; import cacheUserId from "../common/cacheUserId.mjs"; import { getObjIncludes, getUserIncludeIds, } from "../../common/addObjIncludes.mjs"; export default defineSource({ ...common, key: "twitter-new-unfollower-of-user", name: "New Unfollower of User", description: `Emit new event when the specified User loses a Follower [See the documentation](${DOCS_LINK})`, version: "2.1.0", type: "source", props: { ...common.props, userNameOrId: { propDefinition: [ common.props.app, "userNameOrId", ], }, }, methods: { ...common.methods, ...cacheUserId, getItemSummary, getEntityName() { return "Unfollower"; }, getSavedUsers() { return this.db.get("savedUsers"); }, setSavedUsers(data) { this.db.set("savedUsers", data); }, async getResources() { const userId = await this.getCachedUserId(); const params = { $: this, maxPerPage: MAX_RESULTS_PER_PAGE, maxResults: MAX_RESULTS_PER_PAGE, userId, }; const { data, includes, } = await this.app.getUserFollowers(params); data.forEach((user) => user.includes = getObjIncludes(user, includes, getUserIncludeIds)); return data; }, async getAndProcessData(emit = false) { const data = await this.getResources(emit); if (data) { let savedUsers = this.getSavedUsers(); if (savedUsers && emit) { const currentFollowerIds = data.map(({ id }) => id); if (data.length === MAX_RESULTS_PER_PAGE) { const lastKnownFollower = Array.from(data) .reverse() .find(({ id }) => currentFollowerIds.includes(id)); const lastKnownIndex = savedUsers.indexOf(lastKnownFollower); savedUsers = savedUsers.slice(0, lastKnownIndex + 1); } savedUsers .filter(({ id }) => !currentFollowerIds.includes(id)) .reverse() .forEach((obj) => { if (emit) this.emitEvent(obj); }); } this.setSavedUsers(data.map(({ id, username, }) => ({ id, username, }))); } }, }, });