Skip to content

Commit

Permalink
Merge pull request #31 from baquan1708/feat/support-win
Browse files Browse the repository at this point in the history
Update project template when creating with CLI
  • Loading branch information
koichimurakami authored Oct 17, 2024
2 parents 8e74f57 + 19fce0b commit 934892f
Show file tree
Hide file tree
Showing 8 changed files with 215 additions and 17 deletions.
3 changes: 0 additions & 3 deletions packages/cli/templates/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,6 @@ $ npm run build
# docker, open in other terminal session
$ npm run offline:docker

# create resources such as S3 buckets
$ sh infra-local/resources.sh

# migrate tables, open in other terminal session
$ npm run migrate

Expand Down
11 changes: 0 additions & 11 deletions packages/cli/templates/infra-local/resources.sh

This file was deleted.

25 changes: 25 additions & 0 deletions packages/cli/templates/infra-local/scripts/resources.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Load environment variables from .env file (assuming you have a utility to load it)
Get-Content .env | ForEach-Object {
if ($_ -match "^\s*#") {
return
}
if ($_ -match "^\s*(\w+)\s*=\s*(.*)\s*$") {
$name = $matches[1]
$value = $matches[2]
$value = $value -replace '\s*#.*', ''
[System.Environment]::SetEnvironmentVariable($name, $value, "Process")
}
}

Write-Host "======= check if S3 bucket exists ======="
$bucketExists = aws --endpoint-url=http://localhost:4566 s3 ls | Select-String $env:S3_BUCKET_NAME

if (-not $bucketExists) {
Write-Host "Bucket $env:S3_BUCKET_NAME does not exist. Creating it..."
aws --endpoint-url=http://localhost:4566 s3 mb "s3://$env:S3_BUCKET_NAME"
} else {
Write-Host "Bucket $env:S3_BUCKET_NAME already exists."
}

Write-Host "======= list S3 buckets ======="
aws --endpoint-url=http://localhost:4566 s3 ls
19 changes: 19 additions & 0 deletions packages/cli/templates/infra-local/scripts/resources.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/bin/sh

# Load environment variables from .env file
if [ -f .env ]; then
export $(echo $(cat .env | sed 's/#.*//g' | xargs) | envsubst)
fi

echo "======= check if S3 bucket exists ======="
bucket_exists=$(aws --endpoint-url=http://localhost:4566 s3 ls | grep "$S3_BUCKET_NAME" | wc -l)

if [ "$bucket_exists" -eq 0 ]; then
echo "Bucket $S3_BUCKET_NAME does not exist. Creating it..."
aws --endpoint-url=http://localhost:4566 s3 mb s3://$S3_BUCKET_NAME
else
echo "Bucket $S3_BUCKET_NAME already exists."
fi

echo "======= list S3 buckets ======="
aws --endpoint-url=http://localhost:4566 s3 ls
133 changes: 133 additions & 0 deletions packages/cli/templates/infra-local/scripts/trigger_ddb_stream.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Set AWS environment variables
$env:AWS_DEFAULT_REGION = "ap-northeast-1"
$env:AWS_ACCOUNT_ID = "101010101010"
$env:AWS_ACCESS_KEY_ID = "local"
$env:AWS_SECRET_ACCESS_KEY = "local"

$endpoint = "http://localhost:8000"

# Load environment variables from .env file (assuming you have a utility to load it)
Get-Content .env | ForEach-Object {
if ($_ -match "^\s*#") {
return
}
if ($_ -match "^\s*(\w+)\s*=\s*(.*)\s*$") {
$name = $matches[1]
$value = $matches[2]
$value = $value -replace '\s*#.*', ''
[System.Environment]::SetEnvironmentVariable($name, $value, "Process")
}
}

Write-Host "Read table name"

# Read table names from JSON file
$tables = (Get-Content .\prisma\dynamodbs\cqrs.json | ConvertFrom-Json)

# Check table health
$start = Get-Date
foreach ($table in $tables) {
while ($true) {
$elapsed = (New-TimeSpan -Start $start).TotalSeconds
if ($elapsed -gt 10) {
Write-Host "Timeout"
exit 1
}

Write-Host "Check health table local-$env:APP_NAME-$table-command"
Write-Host "local-$env:APP_NAME-$table-command"
$status = aws --endpoint $endpoint dynamodb describe-table --table-name "local-$env:APP_NAME-$table-command" --query "Table.TableStatus"

Write-Host "Table status: $status"
if ($status -eq '"ACTIVE"') {
Write-Host "Table $table is ACTIVE"
break
} else {
Write-Host "Table $table is not ACTIVE"
Start-Sleep -Seconds 1
}
}
}

# Check the health of 'tasks' table
$start = Get-Date
while ($true) {
$elapsed = (New-TimeSpan -Start $start).TotalSeconds
if ($elapsed -gt 10) {
Write-Host "Timeout"
exit 1
}

Write-Host "Check health table tasks"
$status = aws --endpoint $endpoint dynamodb describe-table --table-name "local-$env:APP_NAME-tasks" --query "Table.TableStatus"

Write-Host "Table status: $status"
if ($status -eq '"ACTIVE"') {
Write-Host "Table tasks is ACTIVE"
break
} else {
Write-Host "Table tasks is not ACTIVE"
Start-Sleep -Seconds 1
}
}

# Wait for serverless to start
$start = Get-Date
while ($true) {
$elapsed = (New-TimeSpan -Start $start).TotalSeconds
if ($elapsed -gt 100) {
Write-Host "Timeout"
exit 1
}

Write-Host "Check health serverless"
try {
$response = Invoke-WebRequest -Uri "http://localhost:3000" -UseBasicParsing -ErrorAction Stop
$status = $response.StatusCode
} catch {
if ($_.Exception.Response -ne $null) {
$status = $_.Exception.Response.StatusCode.Value__
} else {
$status = 0 # Assign 0 or another value if there's no HTTP response (e.g., connection failure)
}
}

Write-Host "Serverless status: $status"

if ($status -eq 200) {
Write-Host "Serverless is ACTIVE"
break
} else {
Write-Host "Serverless is not ACTIVE"
Start-Sleep -Seconds 1
}
}


# Trigger command stream
$timestamp = [math]::Round((Get-Date).Subtract((Get-Date "01/01/1970")).TotalSeconds)
foreach ($table in $tables) {
Write-Host "Send a command to trigger command stream $table"
$item = @{
pk = @{ S = "test" }
sk = @{ S = "$timestamp" }
}

# Convert the item to a JSON string with double quotes
$jsonItem = $item | ConvertTo-Json -Compress

$jsonItemString = [string]$jsonItem

$escapedJsonItemString = $jsonItemString -replace '"', '\"'

Write-Host "Send a item to trigger command $table"

aws dynamodb put-item --endpoint http://localhost:8000 --table-name "local-$env:APP_NAME-$table-command" --item $escapedJsonItemString
}

# Trigger asks stream
Write-Host "Send a command to trigger command stream tasks"
$command = @"
aws dynamodb put-item --endpoint http://localhost:8000 --table-name "local-$env:APP_NAME-tasks" --item '{\"input\":{\"M\":{}},\"sk\":{\"S\":\"$timestamp\"},\"pk\":{\"S\":\"test\"}}'
"@
Invoke-Expression $command
23 changes: 23 additions & 0 deletions packages/cli/templates/infra-local/scripts/trigger_ddb_stream.sh
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,26 @@ for table in "${tables[@]}"; do
done
done

start=$(date +%s)
while true; do
elapsed=$(($(date +%s) - ${start}))
if [[ ${elapsed} -gt 10 ]]; then
echo "Timeout"
exit 1
fi

echo "Check health table tasks"
status=$(aws --endpoint=${endpoint} dynamodb describe-table --table-name local-${APP_NAME}-tasks --query 'Table.TableStatus')
echo "Table status: ${status}"
if [[ "${status}" == "\"ACTIVE\"" ]]; then
echo "Table tasks is ACTIVE"
break
else
echo "Table tasks is not ACTIVE"
sleep 1
fi
done

# Wait serverless start
start=$(date +%s)
while true; do
Expand Down Expand Up @@ -67,3 +87,6 @@ for table in "${tables[@]}"; do
echo "Send a command to trigger command stream ${table}"
aws --endpoint=${endpoint} dynamodb put-item --table-name local-${APP_NAME}-${table}-command --item "{\"pk\": {\"S\": \"test\" }, \"sk\": { \"S\": \"${timestamp}\" }}"
done

echo "Send a command to trigger command stream tasks"
aws --endpoint=http://localhost:8000 dynamodb put-item --table-name local-demo-tasks --item "{\"input\":{\"M\":{}},\"sk\":{\"S\":\"${timestamp}\"},\"pk\":{\"S\":\"test\"}}"
1 change: 1 addition & 0 deletions packages/cli/templates/infra-local/serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ provider:
region: ap-northeast-1
runtime: nodejs18.x
profile: serverless
timeout: 100
httpApi:
authorizers:
localAuthorizer:
Expand Down
17 changes: 14 additions & 3 deletions packages/cli/templates/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,18 @@
"build:prod": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start:repl": "nest start --watch --entryFile repl",
"offline:docker:build": "cd infra-local && docker compose up --build --remove-orphans",
"offline:docker": "cd infra-local && mkdir -p docker-data/.cognito && cp -r cognito-local/db docker-data/.cognito && docker compose up --remove-orphans",
"offline:sls": "/bin/bash ./infra-local/scripts/trigger_ddb_stream.sh & ln -f .env $PWD/infra-local/.env && cd infra-local && NODE_ENV=development AWS_ACCESS_KEY_ID=DUMMYIDEXAMPLE AWS_SECRET_ACCESS_KEY=DUMMYEXAMPLEKEY SLS_DEBUG=* serverless offline start",
"offline:docker:build": "run-script-os",
"offline:docker:build:default": "cd infra-local && docker compose up --build --remove-orphans",
"offline:docker:build:win32": "powershell -Command \"Set-Location infra-local; docker compose up --build --remove-orphans\"",
"offline:docker": "run-script-os",
"offline:docker:default": "cd infra-local && mkdir -p docker-data/.cognito && cp -r cognito-local/db docker-data/.cognito && docker compose up --remove-orphans",
"offline:docker:win32": "powershell -Command \"Set-Location infra-local; New-Item -ItemType Directory -Force -Path 'docker-data/.cognito'; Copy-Item -Recurse -Force 'cognito-local/db' 'docker-data/.cognito'; docker compose up --remove-orphans\"",
"offline:sls": "run-script-os",
"offline:sls:default": "/bin/bash ./infra-local/scripts/resources.sh && /bin/bash ./infra-local/scripts/trigger_ddb_stream.sh & ln -f .env $PWD/infra-local/.env && cd infra-local && NODE_ENV=development AWS_ACCESS_KEY_ID=DUMMYIDEXAMPLE AWS_SECRET_ACCESS_KEY=DUMMYEXAMPLEKEY SLS_DEBUG=* serverless offline start",
"offline:sls:win32": "npm run resources:win32 && concurrently \"npm run trigger-ddb:win32\" \"npm run sls:win32\"",
"trigger-ddb:win32": "powershell -ExecutionPolicy Bypass -File ./infra-local/scripts/trigger_ddb_stream.ps1",
"resources:win32": "powershell -ExecutionPolicy Bypass -File ./infra-local/scripts/resources.ps1",
"sls:win32": "powershell -Command \" Copy-Item \".env\" -Destination \".\\infra-local\\.env\" \"; Set-Location infra-local; $env:NODE_ENV='development'; $env:AWS_ACCESS_KEY_ID='DUMMYIDEXAMPLE'; $env:AWS_SECRET_ACCESS_KEY='DUMMYEXAMPLEKEY'; $env:SLS_DEBUG='*'; serverless offline start\"",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
Expand Down Expand Up @@ -60,6 +69,7 @@
"@typescript-eslint/parser": "^6.15.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"concurrently": "^9.0.1",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.29.1",
Expand All @@ -69,6 +79,7 @@
"nestjs-spelunker": "^1.3.0",
"prettier": "^3.1.1",
"prisma": "^5.7.1",
"run-script-os": "^1.1.6",
"serverless": "^3.38.0",
"serverless-dynamodb": "^0.2.47",
"serverless-localstack": "^1.1.2",
Expand Down

0 comments on commit 934892f

Please sign in to comment.