Skip to content

Commit 83da325

Browse files
committed
feat: add examples directory with dotenv support and unified test script
- Add examples directory for local testing - Implement dotenv support for environment variable management - Create unified aws-test.js script that combines all functionality - Add config.js for centralized configuration management - Include comprehensive README with setup instructions - Add .gitignore to protect sensitive .env files
1 parent 5da56ef commit 83da325

8 files changed

Lines changed: 455 additions & 1 deletion

File tree

.gitignore

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ node_modules/
44
coverage/
55
.idea/
66
dist/
7-
examples/
87
.rpt2_cache/
98

109
yarn-error.log

examples/.gitignore

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# 環境設定ファイル
2+
.env
3+
.env.local
4+
.env.*.local
5+
6+
# 依存関係
7+
node_modules/
8+
9+
# ログファイル
10+
*.log
11+
npm-debug.log*
12+
yarn-debug.log*
13+
yarn-error.log*
14+
15+
# 一時ファイル
16+
*.tmp
17+
*.temp
18+
19+
# OS生成ファイル
20+
.DS_Store
21+
Thumbs.db

examples/README.md

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# Lambda@Edge Controller 使用例
2+
3+
このディレクトリには、`lambda-edge-controller`ライブラリの使用方法を示すサンプルスクリプトが含まれています。
4+
5+
## 📁 ファイル一覧
6+
7+
### `aws-test.js` - 統合テストスクリプト
8+
Lambda@Edge Controllerの全機能をテストする統合スクリプトです。
9+
10+
**実行方法:**
11+
```bash
12+
# ライブラリをビルド
13+
npm run build
14+
15+
# スクリプトを実行
16+
node examples/aws-test.js
17+
# または
18+
cd examples && npm test
19+
```
20+
21+
**特徴:**
22+
- **基本テスト**: 各イベントタイプでのコントローラー作成と設定確認
23+
- **高度なテスト**: カスタムCloudFrontクライアントの設定と動作確認
24+
- **AWS環境テスト**: 実際のCloudFrontディストリビューションでの動作確認
25+
- **統合管理**: 1つのスクリプトで全機能をテスト可能
26+
27+
## 🚀 セットアップ手順
28+
29+
### 1. 依存関係のインストール
30+
```bash
31+
# プロジェクトルートで
32+
npm install
33+
# または
34+
yarn install
35+
36+
# examplesディレクトリで
37+
cd examples
38+
npm install
39+
```
40+
41+
### 2. ライブラリのビルド
42+
```bash
43+
# プロジェクトルートで
44+
npm run build
45+
# または
46+
yarn build
47+
```
48+
49+
### 3. 環境設定ファイルの作成
50+
```bash
51+
cd examples
52+
npm run setup
53+
# または
54+
cp env.example .env
55+
```
56+
57+
### 4. .envファイルの設定
58+
`.env`ファイルを編集して、実際の値を設定してください:
59+
60+
```bash
61+
# 必須設定
62+
LAMBDA_ARN=arn:aws:lambda:us-east-1:123456789012:function:my-function:1
63+
CLOUDFRONT_DISTRIBUTION_ID=E1234567890ABCD
64+
65+
# オプション設定
66+
EVENT_TYPE=viewer-request
67+
AWS_REGION=us-east-1
68+
AWS_PROFILE=default
69+
DEBUG=true
70+
```
71+
72+
## ⚠️ 注意事項
73+
74+
### セキュリティ
75+
- 実際のAWS環境でテストする前に、必ずテスト環境で検証してください
76+
- 本番環境のCloudFrontディストリビューションでテストする際は十分注意してください
77+
78+
### 権限
79+
以下のIAM権限が必要です:
80+
- `cloudfront:GetDistribution`
81+
- `cloudfront:UpdateDistribution`
82+
83+
### リージョン
84+
Lambda@Edgeは`us-east-1`リージョンでのみ利用可能です。
85+
86+
## 🧪 テストの流れ
87+
88+
1. **基本テスト**: 各イベントタイプでのコントローラー作成と設定確認
89+
2. **高度なテスト**: カスタムCloudFrontクライアントの設定と動作確認
90+
3. **AWS環境テスト**: 実際のCloudFrontディストリビューションでの動作確認
91+
92+
すべてのテストが1つのスクリプト(`aws-test.js`)で順番に実行されます。
93+
94+
## 🔧 トラブルシューティング
95+
96+
### よくあるエラー
97+
98+
**エラー: "No such distribution"**
99+
- CloudFrontディストリビューションIDが正しいか確認
100+
- 適切なIAM権限があるか確認
101+
102+
**エラー: "AWS認証情報が設定されていない"**
103+
- 環境変数またはAWSプロファイルを設定
104+
- IAMロールを使用している場合は適切な権限があるか確認
105+
106+
**エラー: "Lambda ARNが無効"**
107+
- Lambda関数のARNが正しい形式か確認
108+
- 関数が存在し、適切なバージョンが指定されているか確認
109+
110+
## 📚 参考資料
111+
112+
- [Lambda@Edge公式ドキュメント](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-the-edge.html)
113+
- [CloudFront API リファレンス](https://docs.aws.amazon.com/cloudfront/latest/APIReference/)
114+
- [AWS SDK for JavaScript v3](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/)

examples/aws-test.js

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
const { LambdaEdgeController } = require('../dist/index.js');
2+
const { CloudFrontClient } = require('@aws-sdk/client-cloudfront');
3+
const config = require('./config');
4+
5+
// 統合されたLambda@Edge Controller テストスクリプト
6+
async function runAllTests() {
7+
try {
8+
console.log('🚀 Lambda@Edge Controller の統合テストを開始します...\n');
9+
10+
// 設定の検証
11+
try {
12+
config.validate();
13+
console.log('✅ 設定の検証が完了しました:');
14+
console.log(` Lambda ARN: ${config.lambdaArn}`);
15+
console.log(` CloudFront Distribution ID: ${config.distributionId}`);
16+
console.log(` イベントタイプ: ${config.eventType}\n`);
17+
} catch (error) {
18+
console.error('❌ 設定エラー:', error.message);
19+
console.log('\n💡 .envファイルの設定を確認してください');
20+
console.log(' 例: cp env.example .env で.envファイルを作成し、実際の値を設定してください');
21+
return;
22+
}
23+
24+
// ===== 1. 基本テスト =====
25+
console.log('📋 1. 基本テスト - コントローラーの作成と設定確認');
26+
console.log('-'.repeat(50));
27+
28+
// 各イベントタイプでコントローラーを作成
29+
const eventTypes = ['viewer-request', 'viewer-response', 'origin-request', 'origin-response'];
30+
const controllers = {};
31+
32+
for (const eventType of eventTypes) {
33+
console.log(`\n 📝 ${eventType} イベントタイプでコントローラーを作成中...`);
34+
35+
const lambdaArn = `${config.lambdaArn.replace(/:\d+$/, '')}:${eventType === 'viewer-request' ? '1' : '2'}`;
36+
const controller = new LambdaEdgeController(lambdaArn, eventType);
37+
38+
// デバッグ設定に応じてログを有効化
39+
if (config.debug && eventType === 'viewer-request') {
40+
controller.enableDebugger();
41+
console.log(` 🔍 デバッグログが有効化されました`);
42+
}
43+
44+
controllers[eventType] = controller;
45+
console.log(` ✅ コントローラーが作成されました`);
46+
console.log(` Lambda ARN: ${lambdaArn}`);
47+
console.log(` イベントタイプ: ${controller.getTargetEventType()}`);
48+
}
49+
50+
// ===== 2. 高度なテスト =====
51+
console.log('\n📋 2. 高度なテスト - カスタムCloudFrontクライアントの設定');
52+
console.log('-'.repeat(50));
53+
54+
try {
55+
// カスタム設定でCloudFrontクライアントを作成
56+
const cloudfrontClient = new CloudFrontClient(config.getAwsConfig());
57+
console.log(' ✅ カスタムCloudFrontクライアントが作成されました');
58+
console.log(` AWS設定: ${JSON.stringify(config.getAwsConfig(), null, 2)}`);
59+
} catch (error) {
60+
console.error(' ❌ CloudFrontクライアントの作成に失敗しました:', error.message);
61+
}
62+
63+
// ===== 3. AWS環境テスト =====
64+
console.log('\n📋 3. AWS環境テスト - 実際のCloudFrontディストリビューションでの動作確認');
65+
console.log('-'.repeat(50));
66+
67+
// メインのコントローラーを作成
68+
const mainController = new LambdaEdgeController(config.lambdaArn, config.eventType);
69+
70+
// デバッグ設定に応じてログを有効化
71+
if (config.debug) {
72+
mainController.enableDebugger();
73+
console.log(' 🔍 デバッグログが有効化されました');
74+
}
75+
76+
console.log(' 📋 メインコントローラーが作成されました\n');
77+
78+
// 実際のCloudFrontディストリビューションでテスト
79+
console.log(' 🧪 実際のAWS環境でテストを開始します...\n');
80+
81+
// 現在の設定を確認(アタッチ前)
82+
console.log(' 1️⃣ 現在の設定を確認中...');
83+
try {
84+
// 注意: 実際のCloudFrontディストリビューションにアクセスします
85+
console.log(' ⚠️ 実際のCloudFrontディストリビューションにアクセスします');
86+
console.log(' ⚠️ 適切なIAM権限があることを確認してください\n');
87+
88+
/**/
89+
// 実際のテストを実行する場合は以下のコメントを外してください
90+
91+
// Lambda@Edge関数をアタッチ
92+
console.log(' 2️⃣ Lambda@Edge関数をアタッチ中...');
93+
const attachResult = await mainController.attachEdgeFunction(config.distributionId);
94+
console.log(' ✅ アタッチ完了');
95+
console.log(' 📊 結果:', JSON.stringify(attachResult, null, 2));
96+
97+
// 少し待機(CloudFrontの更新には時間がかかります)
98+
console.log('\n 3️⃣ CloudFrontの更新完了を待機中...(数分かかる場合があります)');
99+
await new Promise(resolve => setTimeout(resolve, 30000)); // 30秒待機
100+
101+
// Lambda@Edge関数をデタッチ
102+
console.log('\n 4️⃣ Lambda@Edge関数をデタッチ中...');
103+
const detachResult = await mainController.detachEdgeFunction(config.distributionId);
104+
console.log(' ✅ デタッチ完了');
105+
console.log(' 📊 結果:', JSON.stringify(detachResult, null, 2));
106+
/**/
107+
108+
console.log(' 📝 実際のテストを実行するには、上記のコメントアウトされたコードを有効化してください');
109+
110+
} catch (error) {
111+
console.error(' ❌ テスト実行中にエラーが発生しました:', error.message);
112+
console.error(' 💡 考えられる原因:');
113+
console.error(' - IAM権限が不足している');
114+
console.error(' - CloudFrontディストリビューションIDが無効');
115+
console.error(' - Lambda関数ARNが無効');
116+
console.error(' - AWS認証情報が設定されていない');
117+
}
118+
119+
console.log('\n🎉 すべてのテストが完了しました!');
120+
121+
} catch (error) {
122+
console.error('❌ エラーが発生しました:', error.message);
123+
console.error('\n💡 .envファイルの設定を確認してください');
124+
console.error(' 例: cp env.example .env で.envファイルを作成し、実際の値を設定してください');
125+
}
126+
}
127+
128+
// 環境変数の設定状況を確認
129+
function checkEnvironment() {
130+
console.log('🔍 設定状況を確認中...\n');
131+
132+
// 設定クラスの表示メソッドを使用
133+
config.display();
134+
}
135+
136+
// スクリプトを実行
137+
if (require.main === module) {
138+
checkEnvironment();
139+
console.log('\n' + '='.repeat(60) + '\n');
140+
runAllTests();
141+
}
142+
143+
module.exports = { runAllTests, checkEnvironment };

examples/config.js

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
const path = require('path');
2+
require('dotenv').config({ path: path.join(__dirname, '.env') });
3+
4+
// 設定値を管理するクラス
5+
class Config {
6+
constructor() {
7+
this.loadEnvironmentVariables();
8+
}
9+
10+
// 環境変数を読み込み
11+
loadEnvironmentVariables() {
12+
// 必須設定
13+
this.lambdaArn = process.env.LAMBDA_ARN;
14+
this.distributionId = process.env.CLOUDFRONT_DISTRIBUTION_ID;
15+
16+
// オプション設定
17+
this.eventType = process.env.EVENT_TYPE || 'viewer-request';
18+
this.awsRegion = process.env.AWS_REGION || 'us-east-1';
19+
this.awsProfile = process.env.AWS_PROFILE;
20+
21+
// AWS認証情報
22+
this.awsAccessKeyId = process.env.AWS_ACCESS_KEY_ID;
23+
this.awsSecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
24+
this.awsSessionToken = process.env.AWS_SESSION_TOKEN;
25+
26+
// デバッグ設定
27+
this.debug = process.env.DEBUG === 'true';
28+
this.logLevel = process.env.LOG_LEVEL || 'info';
29+
}
30+
31+
// 必須設定が揃っているかチェック
32+
validate() {
33+
const errors = [];
34+
35+
if (!this.lambdaArn) {
36+
errors.push('LAMBDA_ARN が設定されていません');
37+
}
38+
39+
if (!this.distributionId) {
40+
errors.push('CLOUDFRONT_DISTRIBUTION_ID が設定されていません');
41+
}
42+
43+
if (errors.length > 0) {
44+
throw new Error(`設定エラー:\n${errors.map(err => ` - ${err}`).join('\n')}`);
45+
}
46+
47+
return true;
48+
}
49+
50+
// 設定状況を表示
51+
display() {
52+
console.log('🔍 現在の設定状況:');
53+
console.log('');
54+
55+
console.log('必須設定:');
56+
console.log(` LAMBDA_ARN: ${this.lambdaArn ? '✅ 設定済み' : '❌ 未設定'}`);
57+
console.log(` CLOUDFRONT_DISTRIBUTION_ID: ${this.distributionId ? '✅ 設定済み' : '❌ 未設定'}`);
58+
console.log('');
59+
60+
console.log('オプション設定:');
61+
console.log(` EVENT_TYPE: ${this.eventType}`);
62+
console.log(` AWS_REGION: ${this.awsRegion}`);
63+
console.log(` AWS_PROFILE: ${this.awsProfile || '未設定'}`);
64+
console.log(` DEBUG: ${this.debug}`);
65+
console.log(` LOG_LEVEL: ${this.logLevel}`);
66+
console.log('');
67+
68+
console.log('AWS認証情報:');
69+
if (this.awsAccessKeyId && this.awsSecretAccessKey) {
70+
console.log(' ✅ 環境変数で設定済み');
71+
} else if (this.awsProfile) {
72+
console.log(` ✅ AWSプロファイル: ${this.awsProfile}`);
73+
} else {
74+
console.log(' ⚠️ 未設定(IAMロールまたはプロファイルを使用してください)');
75+
}
76+
}
77+
78+
// AWS SDK設定オブジェクトを取得
79+
getAwsConfig() {
80+
const config = {
81+
region: this.awsRegion
82+
};
83+
84+
if (this.awsAccessKeyId && this.awsSecretAccessKey) {
85+
config.credentials = {
86+
accessKeyId: this.awsAccessKeyId,
87+
secretAccessKey: this.awsSecretAccessKey
88+
};
89+
90+
if (this.awsSessionToken) {
91+
config.credentials.sessionToken = this.awsSessionToken;
92+
}
93+
}
94+
95+
if (this.awsProfile) {
96+
config.profile = this.awsProfile;
97+
}
98+
99+
return config;
100+
}
101+
}
102+
103+
// シングルトンインスタンスを作成
104+
const config = new Config();
105+
106+
module.exports = config;

0 commit comments

Comments
 (0)