All files / lib/lambda deleteTriggers.ts

90.32% Statements 28/31
50% Branches 2/4
66.66% Functions 2/3
93.33% Lines 28/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                1x 3x 3x     3x 3x 3x   1x 1x   3x       1x 3x     3x 3x 3x     2x 1x 1x 1x         1x       2x 1x 1x 1x 1x 1x       1x 1x     1x      
import { Handler } from "aws-lambda";
import {
  DeleteEventSourceMappingCommand,
  GetEventSourceMappingCommand,
  LambdaClient,
  ListEventSourceMappingsCommand,
} from "@aws-sdk/client-lambda";
 
export const handler: Handler = async (event, _, callback) => {
  console.log("request:", JSON.stringify(event, undefined, 2));
  const response = {
    statusCode: 200,
  };
  let errorResponse = null;
  try {
    await deleteAllTriggersForFunctions(event.functions);
  } catch (error: any) {
    response.statusCode = 500;
    errorResponse = error;
  } finally {
    callback(errorResponse, response);
  }
};
 
export const deleteAllTriggersForFunctions = async (functions: string[]) => {
  const lambdaClient = new LambdaClient({
    region: process.env.region,
  });
  const uuidsToCheck = [];
  for (const functionName of functions) {
    const response = await lambdaClient.send(
      new ListEventSourceMappingsCommand({ FunctionName: functionName }),
    );
    for (const eventSourceMapping of response.EventSourceMappings || []) {
      Eif (eventSourceMapping.SelfManagedKafkaEventSourceConfig) {
        console.log(`Disabling all Kafka triggers for function:  ${functionName}`);
        await lambdaClient.send(
          new DeleteEventSourceMappingCommand({
            UUID: eventSourceMapping.UUID,
          }),
        );
        uuidsToCheck.push(eventSourceMapping.UUID);
      }
    }
  }
  for (const uuid of uuidsToCheck) {
    let deleted = false;
    while (!deleted) {
      const listCommand = new GetEventSourceMappingCommand({ UUID: uuid });
      try {
        await lambdaClient.send(listCommand);
        console.log(`Waiting for mapping ${uuid} to be enabled...`);
        await new Promise((resolve) => setTimeout(resolve, 10000));
      } catch (error) {
        console.log(error);
        deleted = true;
      }
    }
    console.log(`Mapping ${uuid} is now deleted.`);
  }
};