async function handleConnectionControl()

in source/lambda/connection-builder/index.ts [125:177]


async function handleConnectionControl(connectionDefinition: ConnectionBuilderTypes.ConnectionDefinition) {
  const { control, connectionName } = connectionDefinition;

  switch (control) {
    /**
     * When updating, deploying or deleting connections, it invokes the Greengrass deployer Lambda function
     * because at the end of the process, it requires to deploy the Greengrass group
     * and it could take a long time so the API call can be timed out.
     */
    case ConnectionBuilderTypes.ConnectionControl.UPDATE:
    case ConnectionBuilderTypes.ConnectionControl.DEPLOY:
    case ConnectionBuilderTypes.ConnectionControl.DELETE:
      try {
        await dynamoDbHandler.getConnection(connectionName);

        // If the connection control is `deploy`, the connection ID should not exist.
        if (control === ConnectionBuilderTypes.ConnectionControl.DEPLOY) {
          throw new LambdaError({
            message: `\`${connectionName}\` already exists.`,
            name: 'ConnectionBuilderError',
            statusCode: 409
          });
        }
      } catch (error) {
        /**
         * If the connection control is not `deploy`, whenever any error happens, it throws an error.
         * If the connection control is `deploy` and if the error is not `LambdaError`, which is `${connectionName} does not exist.`,
         * it throws an error as it is expected that the DynamoDB client throws an error.
         */
        if ((control !== ConnectionBuilderTypes.ConnectionControl.DEPLOY)
          || (control === ConnectionBuilderTypes.ConnectionControl.DEPLOY && error.message !== `\`${connectionName}\` does not exist.`)) {
          throw error;
        }
      }

      await lambdaHandler.invokeGreengrassDeployer(connectionDefinition);

      return {
        connectionName,
        control,
        message: `Success to request to ${control} the connection: ${connectionName}. It takes time since it's running in the background.`
      };

    /**
     * As control validation check has been done in the previous step, `default` processes the connection.
     * When starting, stoping, pushing, or pulling connections, it publishes a message to the IoT topic
     * so that the Greengrass edge device can process the connection for OPC DA.
     * For OPC UA, it controls the IoT Sitewise gateway configuration or DynamoDB table.
     */
    default:
      return processConnection(connectionDefinition);
  }
}