Serverless Framework に触れて学んだ事を忘れがちな自分の為に備忘録として残します。
やること
まずは API Gateway と Lambda 関数をローカルで開発する方法を学びます。いちいち Lambda の handler を zip して upload して実行するのは時間がかかって大変です。
というわけでローカルで実行して開発するようにします。
今回は API Gateway と Lambda の話です。React はまだ出てきません。
準備
sls create --template aws-nodejs --path serverless-tutorial-one && cd $_
yarn init -y
yarn add serverless-offline --dev
serverless.yml
を以下のように修正します。
service: serverless-tutorial-one
plugins:
- serverless-offline
provider:
name: aws
runtime: nodejs6.10
stage: dev
region: ap-northeast-1
functions:
hello:
handler: handler.hello
events:
- http:
path: hello
method: get
起動
serverless offline
curl http://localhost:3000/hello
を実行して動作確認をします。
もしうまく動かない場合は別のプロセスが :3000
を使用している可能性があるので lsof -i :3000
などをして確認すると良いでしょう。
無事動いたら、これで API Gateway で HTTP Request を受け取り、そのイベントを Lambda に渡して実行結果を HTTP Response で返す、という処理ができました。(ついでにその時のログは Amazon CloudWatch Logs に書き込まれます)
というわけで API Gateway -> Lambda
まではこれでできました。
Lambda で実際に使われる引数を取得する
今から説明することは、もし必要でしたらこういう方法がありますよ、ぐらいに考えて頂ければと思います。
Lambda 関数をローカルで実行するには以下のようにすればよいです。
sls invoke local -f hello
{
"statusCode": 200,
"body": "{\"message\":\"Go Serverless v1.0! Your function executed successfully!\",\"input\":\"\"}"
}
なので以下のように console.log
を仕込んでおけば mock object を取得できます。
'use strict';
module.exports.hello = (event, context, callback) => {
+ console.log(JSON.stringify(event));
+ console.log(JSON.stringify(context));
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'Go Serverless v1.0! Your function executed successfully!',
input: event,
}),
};
callback(null, response);
// Use this code if you don't use the http event with the LAMBDA-PROXY integration
// callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};
ローカルで実行すると結果は以下のようになります。event は空で context が取得できました。
% sls invoke local -f hello
""
{"awsRequestId":"id","invokeid":"id","logGroupName":"/aws/lambda/serverless-tutorial-one-dev-hello","logStreamName":"2015/09/22/[HEAD]13370a84ca4ed8b77c427af260","functionVersion":"HEAD","isDefaultFunctionVersion":true,"functionName":"serverless-tutorial-one-dev-hello","memoryLimitInMB":"1024"}
{
"statusCode": 200,
"body": "{\"message\":\"Go Serverless v1.0! Your function executed successfully!\",\"input\":\"\"}"
}
実際に deploy してから以下を実行すると AWS で動作した場合の引数を取得できます。
serverless deploy
API を叩いてから以下を実行するとより本番に即した mock object を作れると思います。
serverless logs -f hello
上記の説明はこちらを参考にしました。
https://serverless.com/blog/how-test-serverless-applications/
テストするには他にも色々な方法がありそう
https://qiita.com/horike37/items/f0d7e1cf8139c9fb8302
remove
作業が終わったら remove しましょう
serverless remove
まとめ
というわけで API Gateway と Lambda を使いたい場合はこのようにして開発すると動作確認がしやすくて良いのでは無いかと思います。
次回は DynamoDB について説明します。