APIGateway から Lambda を呼び出す場合に、統合タイプで Lambda 関数
を選択すると常に同期呼び出しになってしまう。
非同期で Lambda を呼び出すには統合タイプで AWS サービス
を選択する必要がある。
HTTPヘッダーで X-Amz-Invocation-Type: 'Event'
を設定する。
application/x-www-form-urlencoded
のマッピングテンプレートを設定する。
#set($rawAPIData = $input.path('$'))
## escape any quotes
#set($rawAPIData = $rawAPIData.replace('"', '\"'))
## first we get the number of "&" in the string, this tells us if there is more than one key value pair
#set($countAmpersands = $rawAPIData.length() - $rawAPIData.replace("&", "").length())
## if there are no "&" at all then we have only one key value pair.
## we append an ampersand to the string so that we can tokenise it the same way as multiple kv pairs.
## the "empty" kv pair to the right of the ampersand will be ignored anyway.
#if ($countAmpersands == 0)
#set($rawPostData = $rawAPIData + "&")
#end
## now we tokenise using the ampersand(s)
#set($tokenisedAmpersand = $rawAPIData.split("&"))
## we set up a variable to hold the valid key value pairs
#set($tokenisedEquals = [])
## now we set up a loop to find the valid key value pairs, which must contain only one "="
#foreach( $kvPair in $tokenisedAmpersand )
#set($countEquals = $kvPair.length() - $kvPair.replace("=", "").length())
#if ($countEquals == 1)
#set($kvTokenised = $kvPair.split("="))
#if ($kvTokenised[0].length() > 0)
## we found a valid key value pair. add it to the list.
#set($devNull = $tokenisedEquals.add($kvPair))
#end
#end
#end
{
"headers" : {
#foreach( $key in $input.params().header.keySet() )
"$key" : "$input.params().header.get($key)"#if( $foreach.hasNext ),#end
#end
},
"querystring" : {
#foreach( $kvPair in $tokenisedEquals )
## finally we output the JSON for this pair and append a comma if this isn't the last pair
#set($kvTokenised = $kvPair.split("="))
#if($kvTokenised.size() == 2 && $kvTokenised[1].length() > 0)
#set($kvValue = $kvTokenised[1])
#else
#set($kvValue = "")
#end
#if( $foreach.hasNext )
#set($itemDelimiter = ",")
#else
#set($itemDelimiter = "")
#end
"$kvTokenised[0]" : "$kvValue"$itemDelimiter
#end
},
"stage" : "$context.stage",
"sourceIp" : "$context.identity.sourceIp",
"userAgent" : "$context.identity.userAgent"
}
これでデプロイすれば、非同期で API Gateway から Lambda 関数を呼び出すことができるはずです。