async function cleanupPreviousSubscriptions()

in source/appsync-lambda-resolver/index.ts [245:292]


async function cleanupPreviousSubscriptions(currentSubscriptionsForEvent: IAvaTopicSubscription[], previousSms: string, previousEmail: string, eventId: string): Promise<void> {
  logger.log(LogLevel.INFO, 'Checking if event had previous subscriptions that need to be cleaned');

  const subscriptionsToClean: IAvaTopicSubscription[] = [];

  if (previousEmail) {
    for (const email of previousEmail.split(',')) {
      // Check if previous email subscription is not included in the current list of subscriptions
      if (!currentSubscriptionsForEvent.some(s => s.protocol === SubscriptionProtocols.EMAIL && s.endpoint === email.trim())) {
        subscriptionsToClean.push({ protocol: SubscriptionProtocols.EMAIL, endpoint: email.trim() })
      }
    }
  }

  if (previousSms) {
    for (const phoneNumber of previousSms.split(',')) {
      // Check if previous phone number subscription is not included in the current list of subscriptions
      if (!currentSubscriptionsForEvent.some(s => s.protocol === SubscriptionProtocols.SMS && s.endpoint === phoneNumber.trim())) {
        subscriptionsToClean.push({ protocol: SubscriptionProtocols.SMS, endpoint: phoneNumber.trim() })
      }
    }
  }

  logger.log(LogLevel.INFO, `Found ${subscriptionsToClean.length} subscription(s) to clean`);

  for (let i = 0; i < subscriptionsToClean.length; i++) {
    logger.log(LogLevel.INFO, `Handling #${i + 1} of ${subscriptionsToClean.length} subscription(s) to clean`);

    const subscription = await getSubscriptionFromDataHierarchyTable(subscriptionsToClean[i]);
    if (subscription && subscription.filterPolicy) {
      const eventIdIndex = subscription.filterPolicy.eventId.findIndex(e => e === eventId);

      if (eventIdIndex > -1) {
        // Remove the event ID from the existing filter policy
        subscription.filterPolicy.eventId.splice(eventIdIndex, 1);

        await updateSubscriptionFilterPolicy(subscription);
        await persistSubscriptionInDataHierarchyTable(subscription);
      } else {
        logger.log(LogLevel.WARN, 'Previous subscription from data hierarchy table did not include the current event ID');
        logger.log(LogLevel.VERBOSE, 'Previous subscription from data hierarchy table', JSON.stringify(subscription, null, 2));
      }
    } else {
      logger.log(LogLevel.WARN, 'Previous subscription either did not exist in the data hierarchy table or there was no filter policy');
      logger.log(LogLevel.VERBOSE, 'Previous subscription from data hierarchy table', JSON.stringify(subscription, null, 2));
    }
  }
}