All files / lib/backend-operations/appsync-operations ops-appsync-create.js

83.41% Statements 191/229
57.53% Branches 42/73
98.21% Functions 55/56
83.41% Lines 191/229

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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449                          24x 24x 24x 24x 24x 24x   24x   24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   24x 24x   24x     1x   1x 1x 1x   1x 1x   1x                               1x 1x 1x                   1x         1x 1x 1x 1x 1x 1x 1x 1x 1x   1x       1x 1x 1x                 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x               1x 1x 1x 1x 1x         1x 1x             1x       1x 1x 1x 1x 1x 1x 1x 1x     1x 1x         1x 1x 1x 1x 1x         1x 1x             1x 1x 1x 1x 1x 1x     1x 1x         1x 1x 1x 1x 1x         1x 1x             1x 1x 1x     1x       1x       1x   1x 1x         1x 1x             1x 1x 1x       1x 1x 1x         1x 1x             1x 1x 1x 1x     1x             1x 1x 1x 1x 1x       1x 1x         1x 1x             1x     1x 1x   1x     1x       1x   1x 1x         1x 1x             1x 1x 1x 1x   1x 1x         1x 1x     1x   1x   1x 1x         1x 1x             1x 1x     1x 1x 1x   1x 1x           1x 1x     1x     1x       1x 1x 1x       1x 1x             1x 1x 1x 1x 1x                     1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x       1x 1x 1x         1x         24x      
/* 
 * 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 ora = require('ora')
const path = require('path')
const chalk = require('chalk')
const moment = require('moment')
const util = require('util')
 
const _featureName = 'appsync'
 
const appsyncManager = require('./appsync-manager.js')
const helperServiceRole = require('./helpers/helper-serviceRoles.js')
const helperDynamoDB = require('./helpers/helper-dynamoDB.js')
const appsyncWaitLogic = require('./helpers/appsync-wait-logic.js')
const awsClient = require('../../aws-operations/aws-client.js')
const pathManager = require('../../utils/awsmobilejs-path-manager.js')
const nameManager = require('../../utils/awsmobilejs-name-manager.js')
const dfOps = require('../../utils/directory-file-ops.js')
const projectInfoManager = require('../../project-info-manager.js')
const awsmobilejsConstant = require('../../utils/awsmobilejs-constant.js')
const awsConfigManager = require('../../aws-operations/aws-config-manager.js')
 
const authTypes = ["API_KEY", "AWS_IAM", "AMAZON_COGNITO_USER_POOLS"]
const dataSourceType = ["AWS_LAMBDA", "AMAZON_DYNAMODB", "AMAZON_ELASTICSEARCH"]
 
let spinner = ora('creating appsync ...')
 
function run(projectInfo, awsDetails){
  spinner.start()
 
  let appsyncInfo = appsyncManager.getAppSyncInfo(projectInfo.ProjectPath)
  Eif(!appsyncInfo){
    appsyncInfo = {}
  }
  appsyncInfo.lastPushSuccessful = false
  appsyncManager.setAppSyncInfo(projectInfo.ProjectPath, appsyncInfo)
 
  return setupHandle(projectInfo, awsDetails)
          .then(createDDBTables)
          .then(waitForDDBTableCreationsToComplete)
          .then(createServiceRoles)
          .then(putRolePolicies)
          .then(createGraphqlApi)
          .then(startSchemaCreation)
          .then(waitForSchemaCreationToComplete)
          .then(createDataSources)
          .then(createResolvers)
          .then(createApiKeys)
          .then(onSuccess)
          .catch(onFailure)
}
 
function setupHandle(projectInfo, awsDetails){
  spinner.start('creating appsync: setup handle...')
  return new Promise((resolve, reject) => {
    let appsyncCreationHandle = {
      projectInfo,
      awsDetails,
      featureDirPath: pathManager.getBackendFeatureDirPath(projectInfo.ProjectPath, _featureName),
      apiKeys: appsyncManager.getApiKeys(projectInfo.ProjectPath),
      dataSources: appsyncManager.getDataSources(projectInfo.ProjectPath),
      graphqlApi: appsyncManager.getGraphqlApi(projectInfo.ProjectPath),
      resolvers: appsyncManager.getResolvers(projectInfo.ProjectPath),
      schema: appsyncManager.getSchema(projectInfo.ProjectPath)
    }
    resolve(appsyncCreationHandle)
  })
}
 
function createDDBTables(appsyncCreationHandle){
  spinner.start('creating appsync: create DynamoDB tables' + chalk.blue('(this may take a while)'))
  mapDDBConnections(appsyncCreationHandle)
  let createTableTasks = []
  let tableNameSuffix = nameManager.makeid(8)
  appsyncCreationHandle.dataSources.tables.forEach(table => {
    Eif(table.dataSources && table.dataSources.length>0){
      table.TableName = table.TableName.replace(awsmobilejsConstant.Suffix, tableNameSuffix)
      table.dataSources.forEach(dataSource=>{
        dataSource.dynamodbConfig.tableName = table.TableName
      })
      createTableTasks.push(createDDBTable(appsyncCreationHandle, table))
    }
  })
 
  Eif(createTableTasks.length>0){
    return Promise.all(createTableTasks).then((values)=>{
      return appsyncCreationHandle
    })
  }else{
    return appsyncCreationHandle
  }
}
 
 
function mapDDBConnections(appsyncCreationHandle){
  let dataSources = appsyncCreationHandle.dataSources.dataSources
  let tables = appsyncCreationHandle.dataSources.tables
  dataSources.forEach(dataSource =>{
    Eif(dataSource.type == 'AMAZON_DYNAMODB'){
      for(let i=0; i<tables.length; i++){
        let table = tables[i]
        Eif(table.TableName == dataSource.dynamodbConfig.tableName &&
          table.Region == dataSource.dynamodbConfig.awsRegion){
            dataSource.table = table
            Eif(!table.dataSources){
              table.dataSources = []
            }
            table.dataSources.push(dataSource)
            break
          }
      }
    }
  })
}
 
function createDDBTable(appsyncCreationHandle, table){
  return new Promise((resolve, reject) => {
    let param = helperDynamoDB.constructCreateParam(table)
    let dynamoDBClient = awsClient.DynamoDB(appsyncCreationHandle.awsDetails, table.Region)
    dynamoDBClient.createTable(param, (err, data)=>{
      Iif(err){
        console.log(chalk.red('Failed to create dynamoDB table ' + param.TableName))
        console.log(err)
        reject(err)
      }else{
        table.details = data.TableDescription
        resolve(appsyncCreationHandle)
      }
    })
  })
}
 
function waitForDDBTableCreationsToComplete(appsyncCreationHandle){
  return appsyncWaitLogic.waitForDDBTables(appsyncCreationHandle)
}
 
function createServiceRoles(appsyncCreationHandle){
  spinner.start('creating appsync: create service roles...')
  let createRoleTasks = []
  let roleNameSuffix = nameManager.makeid(6)
  appsyncCreationHandle.dataSources.dataSources.forEach(dataSource => {
    Eif(dataSource.type == 'AMAZON_DYNAMODB' && dataSource.serviceRoleArn == awsmobilejsConstant.ByAWSMobileCLI){
      let tableName = dataSource.dynamodbConfig.tableName
      dataSource.serviceRoleSpec = helperServiceRole.constructCreateRoleParamForDDB(tableName, roleNameSuffix)
      createRoleTasks.push(createServiceRole(appsyncCreationHandle, dataSource))
    }
  })
  return Promise.all(createRoleTasks).then((values)=>{
    return appsyncCreationHandle
  })
}
 
function createServiceRole(appsyncCreationHandle, dataSource){
  return new Promise((resolve, reject) => {
    let param = dataSource.serviceRoleSpec
    let iamClient = awsClient.IAM(appsyncCreationHandle.awsDetails)
    iamClient.createRole(param, (err, data)=>{
      Iif(err){
        console.log(chalk.red('Failed to create service roles ' + param.RoleName))
        console.log(err)
        reject(err)
      }else{
        dataSource.serviceRoleDetails = data
        resolve(appsyncCreationHandle)
      }
    })
  })
}
 
function putRolePolicies(appsyncCreationHandle){
  spinner.start('creating appsync: put service roles policies...')
  let putRolePolicyTasks = []
  appsyncCreationHandle.dataSources.dataSources.forEach(dataSource => {
    Eif(dataSource.type == 'AMAZON_DYNAMODB'){
      dataSource.putServiceRoleSpec = helperServiceRole.constructPutRolePolicyParamForDDB(dataSource)
      putRolePolicyTasks.push(putRolePolicy(appsyncCreationHandle, dataSource))
    }
  })
  return Promise.all(putRolePolicyTasks).then((values)=>{
    return appsyncCreationHandle
  })
}
 
function putRolePolicy(appsyncCreationHandle, dataSource){
  return new Promise((resolve, reject) => {
    let param = dataSource.putServiceRoleSpec
    let iamClient = awsClient.IAM(appsyncCreationHandle.awsDetails)
    iamClient.putRolePolicy(param, (err, data)=>{
      Iif(err){
        console.log(chalk.red('put service role policy err'))
        console.log(err)
        reject(err)
      }else{
        dataSource.putServiceRoleDetails = data
        resolve(appsyncCreationHandle)
      }
    })
  })
}
 
function createGraphqlApi(appsyncCreationHandle){
  spinner.start('creating appsync: create graphql api...')
  return new Promise((resolve, reject) => {
    Iif(appsyncCreationHandle.graphqlApi.name == awsmobilejsConstant.ByAWSMobileCLI){
      appsyncCreationHandle.graphqlApi.name = nameManager.generateGraphqlAPIName(appsyncCreationHandle.projectInfo)
    }
    let param = {
      name: appsyncCreationHandle.graphqlApi.name,
      authenticationType: appsyncCreationHandle.graphqlApi.authenticationType
    }
    Iif(appsyncCreationHandle.graphqlApi.userPoolConfig){
      param.userPoolConfig = appsyncCreationHandle.graphqlApi.userPoolConfig
    }
 
    let appsyncClient = awsClient.AppSync(appsyncCreationHandle.awsDetails)
 
    appsyncClient.createGraphqlApi(param, (err, data)=>{
      Iif(err){
        console.log(chalk.red('create graphal API err ' + param.name))
        console.log(err)
        reject(err)
      }else{
        appsyncCreationHandle.createGraphqlApiResponse = data
        resolve(appsyncCreationHandle)
      }
    })
  })
}
 
function startSchemaCreation(appsyncCreationHandle){
  spinner.start('creating appsync: create schema...')
  return new Promise((resolve, reject) => {
    let param = {
      apiId:  appsyncCreationHandle.createGraphqlApiResponse.graphqlApi.apiId,
      definition: appsyncCreationHandle.schema.definition
    }
    let appsyncClient = awsClient.AppSync(appsyncCreationHandle.awsDetails)
    appsyncClient.startSchemaCreation(param, (err, data)=>{
      Iif(err){
        console.log(chalk.red('startSchemaCreation err '))
        console.log(err)
        reject(err)
      }else{
        appsyncCreationHandle.schemaCreationResponse = data
        resolve(appsyncCreationHandle)
      }
    })
  })
}
 
function waitForSchemaCreationToComplete(appsyncCreationHandle){
  return new Promise((resolve, reject) => {
    let apiId = appsyncCreationHandle.createGraphqlApiResponse.graphqlApi.apiId
    appsyncWaitLogic.waitForSchemaCreation(appsyncCreationHandle, apiId, (err, appsyncCreationHandle)=>{
      Iif(err){
        reject(err)
      }else{
        resolve(appsyncCreationHandle)
      }
    })
  })
}
 
function createDataSources(appsyncCreationHandle){
  spinner.start('creating appsync: create data sources...')
  let createDataSourceTasks = []
  appsyncCreationHandle.dataSources.dataSources.forEach(dataSource => {
    Eif(dataSource.type == 'AMAZON_DYNAMODB' || dataSource.type == "NONE"){
      createDataSourceTasks.push(createDataSource(appsyncCreationHandle, dataSource))
    }
  })
  
  return Promise.all(createDataSourceTasks).then((values)=>{
    return appsyncCreationHandle
  })
}
 
function createDataSource(appsyncCreationHandle, dataSource){
  return new Promise((resolve, reject) => {
    let param = {
      apiId: appsyncCreationHandle.createGraphqlApiResponse.graphqlApi.apiId,
      name: dataSource.name,
      description: dataSource.description,
      type: dataSource.type
    }
 
    Iif(dataSource.serviceRoleDetails && dataSource.serviceRoleDetails.Role && dataSource.serviceRoleDetails.Role.Arn){
      param.serviceRoleArn = dataSource.serviceRoleDetails.Role.Arn
    }
    Eif(dataSource.dynamodbConfig){
      param.dynamodbConfig = dataSource.dynamodbConfig
    }
    Iif(dataSource.lambdaConfig){
      param.lambdaConfig = dataSource.lambdaConfig
    }
    Iif(dataSource.elasticsearchConfig){
      param.elasticsearchConfig = dataSource.elasticsearchConfig
    }
 
    let appsyncClient = awsClient.AppSync(appsyncCreationHandle.awsDetails)
 
    appsyncClient.createDataSource(param, (err, data)=>{
      Iif(err){
        console.log(chalk.red('createDataSource err: ' + param.name))
        console.log(err)
        reject(err)
      }else{
        dataSource.dataSourceDetails = data
        resolve(appsyncCreationHandle)
      }
    })
  })
}
 
function createResolvers(appsyncCreationHandle){
  spinner.start('creating appsync: create resolvers...')
  let createResolverTasks = []
  appsyncCreationHandle.resolvers.forEach(resolver => {
    createResolverTasks.push(createResolver(appsyncCreationHandle, resolver))
  })
  return Promise.all(createResolverTasks).then((values)=>{
    return appsyncCreationHandle
  })
}
 
function createResolver(appsyncCreationHandle, resolver){
  return new Promise((resolve, reject) => {
    let param = {
      apiId: appsyncCreationHandle.createGraphqlApiResponse.graphqlApi.apiId
    }
    Object.assign(param, resolver)
 
    let appsyncClient = awsClient.AppSync(appsyncCreationHandle.awsDetails)
 
    appsyncClient.createResolver(param, (err, data)=>{
      Iif(err){
        console.log(chalk.red('createResolver err: ' + param.fieldName))
        console.log(err)
        reject(err)
      }else{
        resolver.details = data
        resolve(appsyncCreationHandle)
      }
    })
  })
}
 
function createApiKeys(appsyncCreationHandle){
  spinner.start('creating appsync: create api keys...')
  Iif(!appsyncCreationHandle.apiKeys || appsyncCreationHandle.apiKeys.length == 0){
    return appsyncCreationHandle
  }else{
    let createApiKeysTasks = []
    appsyncCreationHandle.apiKeys.forEach(apiKey => {
      createApiKeysTasks.push(createApiKey(appsyncCreationHandle, apiKey))
    })
    return Promise.all(createApiKeysTasks).then((values)=>{
      return appsyncCreationHandle
    })
  }
}
 
function createApiKey(appsyncCreationHandle, apiKey){
  return new Promise((resolve, reject) => {
    let param = {
      apiId:  appsyncCreationHandle.createGraphqlApiResponse.graphqlApi.apiId
    }
    Iif(apiKey.description){
      param.description = apiKey.description
    }
    Iif(apiKey.expires){
      param.expires = apiKey.expires
    }
 
    let appsyncClient = awsClient.AppSync(appsyncCreationHandle.awsDetails)
    appsyncClient.createApiKey(param, (err, data)=>{
      Iif(err){
        console.log(err)
        reject(err)
      }else{
        apiKey.details = data
        resolve(appsyncCreationHandle)
      }
    })
  })
}
 
function onSuccess(appsyncCreationHandle){
  spinner.stop()
  let appsyncInfo = constructAppSyncInfo(appsyncCreationHandle)
  appsyncInfo.lastPushSuccessful = true
  appsyncManager.setAppSyncInfo(appsyncCreationHandle.projectInfo.ProjectPath, appsyncInfo)
  console.log('appsync creation complete: ' + chalk.blue(appsyncCreationHandle.graphqlApi.name))
}
 
function onFailure(e){
  spinner.stop()
  console.log(chalk.red('appsync creation failed'))
  console.log(e)
}
 
function constructAppSyncInfo(appsyncCreationHandle)
{
  let appsyncInfo = {}
 
  appsyncInfo.apiId = appsyncCreationHandle.createGraphqlApiResponse.graphqlApi.apiId
  appsyncInfo.region = appsyncCreationHandle.awsDetails.config.region
  appsyncInfo.name = appsyncCreationHandle.createGraphqlApiResponse.graphqlApi.name
  appsyncInfo.graphqlEndpoint = appsyncCreationHandle.createGraphqlApiResponse.graphqlApi.uris.GRAPHQL
  appsyncInfo.authenticationType = appsyncCreationHandle.createGraphqlApiResponse.graphqlApi.authenticationType
  setApiKey(appsyncInfo, appsyncCreationHandle.apiKeys)
 
  let now = moment().format(awsmobilejsConstant.DateTimeFormatString)
  appsyncInfo.creationTime = now
  appsyncInfo.lastUpdateTime = now
  appsyncInfo.lastSyncTime = now
 
  return appsyncInfo
}
 
function setApiKey(appsyncInfo, apiKeys){
  Eif(apiKeys && apiKeys.length>0){
    let keyWithLogestExpiration = apiKeys[0].details
    for(let i=1; i<apiKeys.length; i++){
      if(apiKeys[i].details.expires > keyWithLogestExpiration.expires){
        keyWithLogestExpiration = apiKeys[i].details
      }
    }
    appsyncInfo.apiKey = keyWithLogestExpiration.id
  }
}
 
 
module.exports = {
  run
}