All files / lib/backend-operations backend-info-manager.js

82.35% Statements 84/102
56.1% Branches 23/41
95% Functions 19/20
82.35% Lines 84/102

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                          10x 10x 10x 10x 10x   10x 10x 10x 10x 10x 10x 10x     1x   1x 1x 1x       1x       1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 1x                           1x 1x 1x 1x 1x           1x 1x           1x 1x 1x 1x 1x   1x 7x 7x     1x   1x   1x         1x         2x 2x 2x 2x 2x 2x 2x 2x                           1x 1x 1x 1x     1x 1x 1x 1x                                                       1x 1x 1x 6x 6x     1x       1x 1x       1x 1x       4x 4x     10x              
/* 
 * 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 chalk = require('chalk')
const inquirer = require('inquirer')
const fs = require('fs-extra')
const os = require('os')
const moment = require('moment')
 
const backendSpecManager = require('./backend-spec-manager.js')
const projectOps = require('./ops-project.js')
const awsExportFileManager = require('../aws-operations/mobile-exportjs-file-manager.js')
const pathManager = require('../utils/awsmobilejs-path-manager.js')
const projectInfoManager = require('../project-info-manager.js')
const awsmobilejsConstant = require('../utils/awsmobilejs-constant.js')
const opsAppSync = require('./ops-appsync.js')
 
function getBackendDetails(projectPath) {
    ensureFolderStructure(projectPath)
    let backendDetails 
    try{
        let backendDetailsFilePath = pathManager.getCurrentBackendDetailsFilePath(projectPath)
        backendDetails = JSON.parse(fs.readFileSync(backendDetailsFilePath, 'utf8'))
    }catch(e){
        console.log(chalk.red('failed to read backend details'))
    }
    return backendDetails
}
 
function clearBackendInfo(projectInfo){
    projectInfoManager.onClearBackend(projectInfo)
    backendSpecManager.onClearBackend(projectInfo)
    awsExportFileManager.onClearBackend(projectInfo)
    fs.emptyDirSync(pathManager.getCurrentBackendInfoDirPath(projectInfo.ProjectPath))
}
 
function syncCurrentBackendInfo(projectInfo, backendDetails, awsDetails, syncToDevFlag, callback) {
    ensureFolderStructure(projectInfo.ProjectPath)
    Eif(backendDetails && backendDetails.projectId && backendDetails.projectId.length > 0){
        console.log('retrieving the latest backend awsmobile project information')
        projectInfo = projectInfoManager.updateBackendProjectDetails(projectInfo, backendDetails)
        setBackendDetails(projectInfo.ProjectPath, backendDetails)
        projectOps.syncCurrentBackendInfo(projectInfo, backendDetails, awsDetails, function(backendProject){
            let enabledFeatures = backendSpecManager.getEnabledFeatures(projectInfo, backendProject)
            Eif(enabledFeatures && enabledFeatures.length > 0){
                let count = 0
                enabledFeatures.forEach(function(featureName){
                    const featureOps = require(pathManager.getOpsFeatureFilePath(featureName))
                    featureOps.syncCurrentBackendInfo(projectInfo, backendDetails, awsDetails, function(){
                        count ++
                        if(count == enabledFeatures.length){
                            onSyncComplete(projectInfo, awsDetails, backendProject, enabledFeatures, syncToDevFlag, callback)
                        }
                    })      
                })
            }else{
                onSyncComplete(projectInfo, awsDetails, backendProject, enabledFeatures, syncToDevFlag, callback)
            }
        })
    }else{
        clearBackendInfo(projectInfo)
    }
}
 
function updateAWSExportFile(projectInfo, awsDetails, callback){ 
    awsExportFileManager.getAWSExportFile(projectInfo, awsDetails, ()=>{
        insertAppSyncJSIntoAWSExportJSFile(projectInfo.ProjectPath)
        let awsExportFilePath = pathManager.getAWSExportFilePath(projectInfo.ProjectPath) 
        let srcDir = pathManager.getSrcDirPath(projectInfo)
        Iif(srcDir && fs.existsSync(srcDir)){
            let srcDirExportFilePath = pathManager.getSrcDirExportFilePath(projectInfo)
            fs.copySync(awsExportFilePath, srcDirExportFilePath)
            console.log('awsmobile project\'s access information copied to: ')
            console.log('    ' + chalk.blue(pathManager.getSrcDirExportFilePath_relative(projectInfo)))    
        }
        Eif(callback){
            callback()
        }
    })
}
 
function insertAppSyncJSIntoAWSExportJSFile(projectPath){
    let appsyncJSObj = opsAppSync.getAppSyncJS(projectPath)
    Eif(appsyncJSObj && Object.keys(appsyncJSObj).length > 0){
        let awsExportFilePath = pathManager.getAWSExportFilePath(projectPath)
        let content = fs.readFileSync(awsExportFilePath).toString()
        let extraContent = ""
 
        Object.keys(appsyncJSObj).forEach(function(key) {
            var val = appsyncJSObj[key]
            extraContent += "    'aws_appsync_" + key + "': '" + val + "'," + os.EOL
        })
        
        let index = content.lastIndexOf('}')
 
        content = content.slice(0, index) + extraContent + content.slice(index)
 
        fs.writeFileSync(awsExportFilePath, content, 'utf8')
    }
}
 
function onProjectConfigChange(projectInfo_old, projectInfo){
    awsExportFileManager.onProjectConfigChange(projectInfo_old, projectInfo)
}
 
 
function setBackendDetails(projectPath, backendDetails, silentFlag) {
    try{    
        ensureFolderStructure(projectPath)
        let backendDetailsFilePath = pathManager.getCurrentBackendDetailsFilePath(projectPath)
        let jsonString = JSON.stringify(backendDetails, null, '\t')
        fs.writeFileSync(backendDetailsFilePath, jsonString, 'utf8')
        Eif(!silentFlag){
            console.log('awsmobile project\'s details logged at:')
            console.log('    ' + chalk.blue(pathManager.getCurrentBackendDetailsFilePath_Relative(projectPath)))
        }
    }catch(e){
        console.log(chalk.red('failed to write backend details'))
    }
}
 
 
//syncToDevFlag
//<0: no sync to backend
//0: prompt for confirmation
//1: sync mobile hub project spec (yaml) 
//>1: sync project spec and feature contents
function onSyncComplete(projectInfo, awsDetails, backendProject, enabledFeatures, syncToDevFlag, callback){
    updateAWSExportFile(projectInfo, awsDetails, ()=>{
        console.log('contents in #current-backend-info/ is synchronized with the latest in the aws cloud')
        updateBackendSyncTime(projectInfo)
        Iif(!syncToDevFlag){
            syncToDevFlag = 0
        }
        Eif(syncToDevFlag > 0){
            syncAllToDev(projectInfo, backendProject, enabledFeatures)
            Eif(callback){
                callback()
            }
        }else if(syncToDevFlag == 0){
            let message = 'sync corresponding contents in backend/ with #current-backend-info/'
            inquirer.prompt([
            {
                type: 'confirm',
                name: 'syncToDevBackend',
                message: message,
                default: false
            }
            ]).then(function (answers) {
                if(answers.syncToDevBackend){
                    syncAllToDev(projectInfo, backendProject, enabledFeatures, true)
                }
                if(callback){
                    callback()
                }
            })
        }else{
            if(callback){
                callback()
            }
        }
    })
}
 
function syncAllToDev(projectInfo, backendProject, enabledFeatures, isConfirmed){
    projectOps.syncToDevBackend(projectInfo, backendProject, enabledFeatures)
    Eif(enabledFeatures && enabledFeatures.length > 0){
        enabledFeatures.forEach(function(featureName){
            const featureOps = require(pathManager.getOpsFeatureFilePath(featureName))
            featureOps.syncToDevBackend(projectInfo, backendProject, enabledFeatures, isConfirmed)
        })
    }
    updateBackendSyncToDevTime(projectInfo)
}
 
function updateBackendSyncTime(projectInfo){
    projectInfo.BackendLastSyncTime = moment().format(awsmobilejsConstant.DateTimeFormatString) 
    projectInfoManager.setProjectInfo(projectInfo)
}
 
function updateBackendSyncToDevTime(projectInfo){
    projectInfo.BackendLastSyncToDevTime = moment().format(awsmobilejsConstant.DateTimeFormatString) 
    projectInfoManager.setProjectInfo(projectInfo)
}
 
function ensureFolderStructure(projectPath){
    const currentBackendInfoDirPath = pathManager.getCurrentBackendInfoDirPath(projectPath)
    fs.ensureDirSync(currentBackendInfoDirPath)
}
 
module.exports = {
    getBackendDetails,
    setBackendDetails,
    clearBackendInfo,
    syncCurrentBackendInfo,
    onProjectConfigChange
}