async createTask()

in source/services/tasks/tasks.ts [272:341]


    async createTask(task: TaskInfo): Promise<TaskReturn | ErrorReturn> {
        let requiredFields = [
            task.name,
            task.targetTag,
            task.accounts,
            task.regions,
            task.actionName,
            task.triggerType
        ];

        // Checks if the fields are empty
        if (!COMMON_UTIL.isStringValuesValid(requiredFields)) {
            return Promise.reject(
                COMMON_UTIL.getErrorObject('CreateTaskFailure', 400, 'Required values cannot be empty.')
            );
        }

        try {
            // Builds a task DynamoDB item and validates parameters
            let item = await this.buildTaskItem(task);

            // Puts a CloudWatch event rule
            // buildTaskItem is going to validate the values, so no more validation is needed.
            await this.putCloudWatchEventRule(item);

            // Generate CloudFormation Template for cross accounts and regions
            let templateUrl = await this.generateCloudFormationTemplate(item);
            item['templateUrl'] = templateUrl;

            const params: DocumentClient.PutItemInput = {
                TableName: this.tasksTable,
                Item: item
            };

            // Inserts item to DynamoDB
            await this.documentClient.put(params).promise();

            // Sends a metric
            if (this.sendAnonymousUsageData === 'Yes') {
                let eventType = true ? 'ScheduledTaskCreated' : 'EventTaskCreated';
                let eventData = {
                    TaskName: task.actionName,
                    AutomationDocumentName: task.actionName,
                    RegionCount: task.regions.split(',').length,
                    AccountCount: task.accounts.split(',').length
                };

                if (task.triggerType === TriggerType.Schedule) {
                    eventData['ScheduleType'] = task.scheduledType;
                    eventData['ScheduleDetails'] = {
                        Interval:
                            task.scheduledType === ScheduledType.CronExpression ?
                                task.scheduledCronExpression :
                                `${task.scheduledFixedRateInterval} ${task.scheduledFixedRateType}`
                    };
                } else if (task.triggerType === TriggerType.Event) {
                    eventData['EventPattern'] = task.eventPattern;
                }

                await COMMON_UTIL.sendAnonymousMetric(this.solutionId, this.solutionVersion, this.solutionUuid, eventType, eventData);
            }

            return Promise.resolve(item);
        } catch (error) {
            LOGGER.error(`createTask Error: ${JSON.stringify(error)}`);
            return Promise.reject(
                COMMON_UTIL.getErrorObject('CreateTaskFailure', 500, 'Error occurred while creating a task.', error)
            );
        }
    }