async function deleteApiKey()

in source/lambda/customresource/customresource.js [225:321]


async function deleteApiKey(event) {
  console.log("[INFO] deleteApiKey start");
  try {
    var api = event.ResourceProperties.APIGateway;

    var apiId = api.Id;
    var apiStage = api.Stage;
    var planName = api.PlanName;
    var keyName = api.Key.Name;
    var keyValue = api.Key.Value;
    var keyId = null;
    var usagePlanIds = [];

    var getApiKeysRequest = {
      nameQuery: keyName,
    };

    var getApiKeysResponse = await apiGateway
      .getApiKeys(getApiKeysRequest)
      .promise();

    console.log("[INFO] got getApiKeys() response: %j", getApiKeysResponse);

    if (getApiKeysResponse.items && getApiKeysResponse.items.length == 1) {
      keyId = getApiKeysResponse.items[0].id;

      var getUsagePlansRequest = {
        keyId: keyId,
      };

      var getUsagePlansResponse = await apiGateway
        .getUsagePlans(getUsagePlansRequest)
        .promise();

      console.log(
        "[INFO] got getUsagePlans() response: %j",
        getUsagePlansResponse
      );

      if (getUsagePlansResponse.items) {
        for (var i = 0; i < getUsagePlansResponse.items.length; ++i) {
          usagePlanIds.push(getUsagePlansResponse.items[i].id);
        }
      }
    }

    console.log("[INFO] found key to delete: %s", keyId);
    console.log("[INFO] found usage plans to delete: %j", usagePlanIds);

    for (var i = 0; i < usagePlanIds.length; i++) {
      var deleteUsagePlanKeyRequest = {
        keyId: keyId,
        usagePlanId: usagePlanIds[i],
      };

      await apiGateway.deleteUsagePlanKey(deleteUsagePlanKeyRequest).promise();

      console.log("[INFO] successfully deleted usage plan key");

      var updateUsagePlanRequest = {
        usagePlanId: usagePlanIds[i],
        patchOperations: [
          {
            from: "STRING_VALUE",
            op: "remove",
            path: "/apiStages",
            value: apiId + ":" + apiStage,
          },
        ],
      };

      await apiGateway.updateUsagePlan(updateUsagePlanRequest).promise();

      console.log("[INFO] removed stage from usage plan");

      var deleteUsagePlanRequest = {
        usagePlanId: usagePlanIds[i],
      };

      await apiGateway.deleteUsagePlan(deleteUsagePlanRequest).promise();

      console.log("[INFO] successfully deleted usage plan: " + usagePlanIds[i]);
    }

    if (keyId) {
      var deleteApiKeyRequest = {
        apiKey: keyId,
      };

      await apiGateway.deleteApiKey(deleteApiKeyRequest).promise();

      console.log("[INFO] successfully deleted API key: " + keyId);
    }
  } catch (error) {
    console.log("[ERROR] failed to delete API key material", error);
  }
}