version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 14
    commands:
      - echo "Deploying functions..."
      - mkdir deployment_package
      - cp -R src/ deployment_package
      - cp -R prisma/ deployment_package
      - cd deployment_package
      - zip -r9 deployment_package.zip .
      - aws lambda update-function-code --function-name $REPO'-'$STAGE --zip-file fileb://deployment_package.zip
      - cd ..
  build:
    commands:
      - |
        if [ "$BUILD_LAYER" = "YES" ]; then
          echo "Building and deploying layers..."
          npm install --production
          npm install prisma@2.29.1 -g
          prisma generate
          cd node_modules/.prisma/client
          find . -type f -name "query-engine*" ! -name 'query-engine-rhel*' -delete
          cd ../../../
          rm -rf node_modules/@prisma/cli
          mkdir -p prisma-layer/nodejs/node_modules/.prisma
          mkdir -p prisma-layer/nodejs/node_modules/@prisma
          cp -r node_modules/.prisma/client prisma-layer/nodejs/node_modules/.prisma
          cp -r node_modules/@prisma prisma-layer/nodejs/node_modules
          cd prisma-layer
          zip -r9 prisma-layer.zip nodejs
          cd ..
          npm install -g node-prune
          node-prune
          npm install modclean -g
          modclean -n default:safe,default:caution -r
          rm -rf node_modules/.prisma
          rm -rf node_modules/@prisma
          rm -rf node_modules/grpc
          rm -rf node_modules/@google-cloud
          rm -rf node_modules/google-gax
          mkdir -p modules-layer/nodejs
          cp -r node_modules modules-layer/nodejs
          cd modules-layer
          zip -r9 modules-layer.zip nodejs
          cd ..
          aws lambda publish-layer-version --layer-name $REPO'-'$STAGE'-modules-layer' --zip-file fileb://modules-layer/modules-layer.zip --compatible-runtimes nodejs14.x --region $REGION > modulesLayer.json
          aws lambda publish-layer-version --layer-name $REPO'-'$STAGE'-prisma-layer' --zip-file fileb://prisma-layer/prisma-layer.zip --compatible-runtimes nodejs14.x --region $REGION > prismaLayer.json
          echo "aws lambda update-function-configuration --function-name $REPO'-'$STAGE --layers $(cat modulesLayer.json | jq '.LayerVersionArn') $(cat prismaLayer.json | jq '.LayerVersionArn')" > update-function-configuration.sh
          chmod +x update-function-configuration.sh
          ./update-function-configuration.sh
        fi
      - |
        if [ "$BUILD_LAYER" = "NO" ]; then
          echo "Skipping layer pipeline..."
        fi
  post_build:
    commands:
      - echo "Success!!"
