All files / lib backend-update.js

98.29% Statements 115/117
76.74% Branches 33/43
100% Functions 19/19
98.29% Lines 115/117

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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229                          4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x                   9x 9x 9x 9x 8x 8x 8x 7x 6x     1x       1x 1x 1x             7x 7x 7x     5x 5x   2x 2x 2x 2x 2x 2x 2x               2x 1x 1x   1x               1x 1x 1x                   6x 6x 6x 6x 6x 6x 6x         9x 9x 9x   9x 9x   9x       9x       9x 9x   9x 9x 9x     9x       9x       6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x         1x         6x       6x   6x   6x         6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 5x 5x 5x 3x 3x 3x 3x 3x 3x 3x 3x       2x 2x                 4x      
/* 
 * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
 * the License. A copy of the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
 * and limitations under the License.
*/
"use strict";
const fs = require('fs-extra')
const chalk = require('chalk')
const ora = require('ora')
const opn = require('opn')
const inquirer = require('inquirer')
const moment = require('moment')
 
const backendRetrieve = require('./backend-retrieve.js')
const projectInfoManager = require('./project-info-manager.js')
const projectBackendBuilder = require('./build-backend.js')
const backendWaitLogic = require('./backend-wait-logic.js')
const opsAppSync = require('./backend-operations/ops-appsync.js')
const backendSpecManager = require('./backend-operations/backend-spec-manager.js')
const backendInfoManager = require('./backend-operations/backend-info-manager.js')
const awsConfigManager = require('./aws-operations/aws-config-manager.js')
const awsClient = require('./aws-operations/aws-client.js')
const awsExceptionHandler = require('./aws-operations/aws-exception-handler.js')
const opsCloudApi = require('./backend-operations/ops-cloud-api.js')
const dfops = require('./utils/directory-file-ops.js')
const pathManager = require('./utils/awsmobilejs-path-manager.js')
const awsmobilejsConstant = require('./utils/awsmobilejs-constant.js')
 
const maxCloudApiWaitLoop = 100 //each wait is 5 seconds
 
let _projectInfo
let _awsDetails
let _backendDetails
let _callback
let _enabledFeatures
let _syncToDevFlag
 
function run(callback) {
    _callback = callback
    _projectInfo = projectInfoManager.getProjectInfo()
    Eif(_projectInfo){
        if(isNewUpdateNeeded()){
            awsConfigManager.checkAWSConfig(function(awsDetails){
                _awsDetails = awsDetails
                if(_projectInfo.BackendProjectID && _projectInfo.BackendProjectID.length > 0){
                    checkLatestInCloud(function(backendDetails){
                        updateBackend(_projectInfo, backendDetails, awsDetails, 1,callback)
                    })
                }else{
                    console.log(chalk.red('backend awsmobile project unknown'))
                }
            })
        }else{
            console.log('No local changes detected for the backend awsmobile project')
            Eif(_callback){
                _callback()
            }
        }
    }
}
 
function checkLatestInCloud(callback){
    backendRetrieve.getLatestBackendDetails(_projectInfo.BackendProjectID, function(backendDetails){
        _backendDetails = backendDetails
        if(projectInfoManager.checkBackendUpdateNoConflict(_projectInfo, backendDetails)){
            //nothing is changed since last pull, but just to make sure the user didn't delete 
            //or modify this file, because it is used by the following push procedure
            backendInfoManager.setBackendDetails(_projectInfo.ProjectPath, backendDetails, true)
            callback(backendDetails)
        }else{
            console.log(chalk.red('the backend awsmobile project is ahead of your local copy'))
            console.log('it might have been updated by others or through other chanels')
            console.log('if you continue with the push, unintended consequences may occur')
            console.log('such as accidental awsmobile feature removal, among others')
            console.log(chalk.gray('# to retrieve the latest details of the backend awsmobile project'))
            console.log('    $ awsmobile pull')
            inquirer.prompt([
                {
                    type: 'confirm',
                    name: 'forcePush',
                    message: "do you want to continue with the push",
                    default: false
                }
            ]).then(function (answers) {
                if(answers.forcePush){
                    backendInfoManager.setBackendDetails(_projectInfo.ProjectPath, backendDetails, true)
                    callback(backendDetails)
                }else{
                    inquirer.prompt([
                        {
                            type: 'confirm',
                            name: 'openConsole',
                            message: "do you want to open the web console of the backend awsmobile project",
                            default: true
                        }
                    ]).then(function (answers) {
                        Eif(answers.openConsole){
                            console.log(chalk.green(backendDetails.consoleUrl))
                            opn(backendDetails.consoleUrl, {wait: false})
                        }
                    })
                }
            })
        }
    })
}
 
function updateBackend(projectInfo, backendDetails, awsDetails, syncToDevFlag, callback){
    _projectInfo = projectInfo
    _backendDetails = backendDetails
    _awsDetails = awsDetails
    _syncToDevFlag = syncToDevFlag
    _callback = callback
    projectBackendBuilder.build(function(){
        preUpdateAction()
    })
}
 
function isNewUpdateNeeded(){
    let ignoredDirs = []
    let ignoredFiles = []
    let backendDirPath = pathManager.getBackendDirPath(_projectInfo.ProjectPath)
    
    let lastBackendDirModificationTime = moment(dfops.getDirContentMTime(backendDirPath, ignoredDirs, ignoredFiles))
    let timeStamp = getTimeStamp(_projectInfo)
 
    let result =!timeStamp.isValid() || 
                !lastBackendDirModificationTime.isValid() ||
                timeStamp.isBefore(lastBackendDirModificationTime) 
    
    return result || opsAppSync.isNewUpdateNeeded(_projectInfo.ProjectPath)
}
 
function getTimeStamp(projectInfo){
    let lastBackendPushTime = moment(projectInfo.BackendLastPushTime, awsmobilejsConstant.DateTimeFormatString)
    let lastBackendSyncToDevTime = moment(projectInfo.BackendLastSyncToDevTime, awsmobilejsConstant.DateTimeFormatString)
 
    let result = lastBackendSyncToDevTime
    Eif(lastBackendPushTime.isValid()){
        Iif(result.isValid()){
            result = lastBackendPushTime > result ? lastBackendPushTime : result
        }else{
            result = lastBackendPushTime
        }
    }
 
    return result
}
 
function preUpdateAction(){
    let count = 0
    _enabledFeatures = backendSpecManager.getEnabledFeatures(_projectInfo)
    if(_enabledFeatures && _enabledFeatures.length > 0){
        console.log()
        console.log('preparing for backend project update: ' + _projectInfo.BackendProjectName)
        _enabledFeatures.forEach(function(featureName){
            const featureOps = require(pathManager.getOpsFeatureFilePath(featureName))
            featureOps.preBackendUpdate(_projectInfo, _backendDetails, _awsDetails,function(){
                count ++
                Eif(count == _enabledFeatures.length){
                    console.log('done')
                    executeUpdate()
                }
            })                
        })
    }else{
        executeUpdate()
    }
}
 
function executeUpdate(){
    opsAppSync.updateApi(_projectInfo, _awsDetails, updateBackendProject)
}
 
function updateBackendProject(){
    let backendContents = fs.readFileSync(pathManager.getBackendContentZipFilePath(_projectInfo.ProjectPath))
    
    let mobile = awsClient.Mobile(_awsDetails)
 
    let param = {
        contents: backendContents,
        projectId: _projectInfo.BackendProjectID
    }
    
    console.log()
    console.log('updating backend project: ' + _projectInfo.BackendProjectName)
    let spinner = ora('calling awsmobile public api method updateProject ...')
    spinner.start()
    mobile.updateProject(param, function(err,data){
        spinner.stop()
        Object.assign(_projectInfo, projectInfoManager.getProjectInfo())
        if(err){
            console.log(chalk.red('Failed to update project ' +  _projectInfo.BackendProjectName))
            awsExceptionHandler.handleMobileException(err)
        }else Eif(data && data.details){
            backendWaitLogic.wait(data.details, _awsDetails, (err, backendDetails) => {
                if(!err){
                    console.log()
                    console.log('Successfully updated the backend awsmobile project: ' + chalk.blue(backendDetails.name))
                    console.log()
                    _projectInfo.BackendLastPushTime = moment().format(awsmobilejsConstant.DateTimeFormatString) 
                    projectInfoManager.setProjectInfo(_projectInfo)
                    backendInfoManager.syncCurrentBackendInfo(_projectInfo, backendDetails, _awsDetails, _syncToDevFlag, function(){
                        Eif(_callback){
                            _callback()
                        }
                    })
                }else{
                    console.log(chalk.red('Failed to update project ' +  _projectInfo.BackendProjectName))
                    process.exit(1)
                }
            })
        }else{
            console.log(chalk.red('something went wrong'))
        }
    })
}
 
module.exports = {
    run, 
    updateBackend
}