0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AWS lambdaでPOST+JSONをテストイベント、Webアプリからのイベントに対応する

Posted at

やりたい事

lambdaにPost+JSONが来た時に、bodyからデータを取り出し変数に格納したいが、
テストイベントとWebアプリからのイベントで別のコードに分けていたので、同じにしたい

テストイベント用のコード

まずテストイベントでは以下のようなJsonを使っていた

{
  "body": {"name":"test","score":0}
}

受け取りの処理は以下のように取得できる

exports.handler = async (event, context) => {
    let bodyMessage = event.body;
    
    let name = bodyMessage.name;
    let score = bodyMessage.score;
}

しかし、Webアプリケーション側でbodyにJSONを付与した場合はJSON.Parseをしないとデータが取得できず、nameとscoreの変数に格納される値は空欄となってしまっていた

Webアプリ用のコード

Jsonの形式は同じなので省略
以下のように取得する

exports.handler = async (event, context) => {
    let bodyMessage = JSON.parse(event.body);
    
    let name = bodyMessage.name;
    let score = bodyMessage.score;
}

JSON.parseをする事でJSONに変換し、変数に値を格納していた。
先ほど作ったテストイベントを使うと以下のようにエラーが起こる

ERROR	Invoke Error 	{"errorType":"SyntaxError","errorMessage":"Unexpected token o in JSON at position 1","stack":["SyntaxError: Unexpected token o in JSON at position 1","    at JSON.parse (<anonymous>)","    at Runtime.exports.handler (/var/task/index.js:10:28)","    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"]}
END RequestId: 554eb535-495a-423c-9c7f-47419d0e8dae

解決策

以下のコードで分岐させる事で解決したが、コードがテスト専用のコードになっているため、良くない。

let bodyMessage = event.body;

//Webアプリケーションからの場合、parseをしないとundefineになる
if(bodyMessage.name===undefined){
    bodyMessage = JSON.parse(event.body);
}

一旦はこの状態で利用しているが、より良い方法が見つかれば追記する。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?