Tengo una función Lambda que está vinculada a API Gateway y estoy tratando de obtener la ruta y el escenario del evento o del objeto de contexto que se pasan a la función Lambda.
La plantilla de mapeo generada por la consola de AWS se encuentra a continuación:
## See http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html ## This template will pass through all parameters including path, querystring, header, stage variables, and context through to the integration endpoint via the body/payload #set($allParams = $input.params()) { "body-json" : $input.json('$'), "params" : { #foreach($type in $allParams.keySet()) #set($params = $allParams.get($type)) "$type" : { #foreach($paramName in $params.keySet()) "$paramName" : "$util.escapeJavaScript($params.get($paramName))" #if($foreach.hasNext),#end #end } #if($foreach.hasNext),#end #end }, "stage-variables" : { #foreach($key in $stageVariables.keySet()) "$key" : "$util.escapeJavaScript($stageVariables.get($key))" #if($foreach.hasNext),#end #end }, "context" : { "stage" : "$context.stage", "source-ip" : "$context.identity.sourceIp", "user" : "$context.identity.user", "user-agent" : "$context.identity.userAgent", "user-arn" : "$context.identity.userArn", "request-id" : "$context.requestId", "resource-id" : "$context.resourceId", "resource-path" : "$context.resourcePath", "account-id" : "$context.identity.accountId", "api-id" : "$context.apiId", "api-key" : "$context.identity.apiKey", "authorizer-principal-id" : "$context.authorizer.principalId", "caller" : "$context.identity.caller", "cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider", "cognito-authentication-type" : "$context.identity.cognitoAuthenticationType", "cognito-identity-id" : "$context.identity.cognitoIdentityId", "cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId", "http-method" : "$context.httpMethod" } }Estoy tratando de obtener el escenario del objeto de contexto de esta manera:
exports.handler = function(event, context) { console.log("Stage: " + context.stage); ... } pero el logcat se muestra como Stage : undefined .
Tengo otros parámetros de consulta que puedo extraer de los parámetros de un objeto de evento como este
var id = event.params.querystring.id; var publisher_id = event.params.querystring.publisher_id;¿Cómo puedo extraer los valores de ruta y etapa del contexto con la plantilla de mapeo anterior?
El valor de stage está disponible en event.context.stage . Así que cambia tu código a esto:
exports.handler = function(event, context) { console.log("Stage: " + event.context.stage); ... }Estamos utilizando una plantilla de mapeo básica que se enumera aquí:
## See http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html ## This template will pass through all parameters including path, querystring, header, stage variables, and context through to the integration endpoint via the body/payload #set($allParams = $input.params()) { "body-json" : $input.json('$'), "params" : { #foreach($type in $allParams.keySet()) #set($params = $allParams.get($type)) "$type" : { #foreach($paramName in $params.keySet()) "$paramName" : "$util.escapeJavaScript($params.get($paramName))" #if($foreach.hasNext),#end #end } #if($foreach.hasNext),#end #end }, "stage-variables" : { #foreach($key in $stageVariables.keySet()) "$key" : "$util.escapeJavaScript($stageVariables.get($key))" #if($foreach.hasNext),#end #end }, "context" : { "account-id" : "$context.identity.accountId", "api-id" : "$context.apiId", "api-key" : "$context.identity.apiKey", "authorizer-principal-id" : "$context.authorizer.principalId", "caller" : "$context.identity.caller", "cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider", "cognito-authentication-type" : "$context.identity.cognitoAuthenticationType", "cognito-identity-id" : "$context.identity.cognitoIdentityId", "cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId", "http-method" : "$context.httpMethod", "stage" : "$context.stage", "source-ip" : "$context.identity.sourceIp", "user" : "$context.identity.user", "user-agent" : "$context.identity.userAgent", "user-arn" : "$context.identity.userArn", "request-id" : "$context.requestId", "resource-id" : "$context.resourceId", "resource-path" : "$context.resourcePath" } }Agregué esta línea "stage":"$context:stage", en la plantilla de mapeo y usé event[stage] para recuperar el valor. Esto funcionó. No olvide volver a implementar la API.
Plantilla de asignación modificada:
## See http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html ## This template will pass through all parameters including path, querystring, header, stage variables, and context through to the integration endpoint via the body/payload #set($allParams = $input.params()) { "body-json" : $input.json('$'), "params" : { #foreach($type in $allParams.keySet()) #set($params = $allParams.get($type)) "$type" : { #foreach($paramName in $params.keySet()) "$paramName" : "$util.escapeJavaScript($params.get($paramName))" #if($foreach.hasNext),#end #end } #if($foreach.hasNext),#end #end }, "stage-variables" : { #foreach($key in $stageVariables.keySet()) "$key" : "$util.escapeJavaScript($stageVariables.get($key))" #if($foreach.hasNext),#end #end }, // added this line "context" : { "stage" : "$context.stage", "source-ip" : "$context.identity.sourceIp", "user" : "$context.identity.user", "user-agent" : "$context.identity.userAgent", "user-arn" : "$context.identity.userArn", "request-id" : "$context.requestId", "resource-id" : "$context.resourceId", "resource-path" : "$context.resourcePath", "account-id" : "$context.identity.accountId", "api-id" : "$context.apiId", "api-key" : "$context.identity.apiKey", "authorizer-principal-id" : "$context.authorizer.principalId", "caller" : "$context.identity.caller", "cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider", "cognito-authentication-type" : "$context.identity.cognitoAuthenticationType", "cognito-identity-id" : "$context.identity.cognitoIdentityId", "cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId", "http-method" : "$context.httpMethod" } }y código:
exports.handler = function(event, context) { console.log("Stage: " + event[stage]); ... }Debe marcar "Integración de proxy Lambda" en la integración de su método en la puerta de enlace API, para recibir la información de la etapa.
Para usar una variable de etapa para personalizar el extremo de integración HTTP, primero debe configurar una variable de etapa con un nombre específico, por ejemplo, url, y luego asignarle un valor, por ejemplo, ejemplo.com. A continuación, desde la configuración de su método, configure una integración de proxy HTTP y, en lugar de ingresar la URL del punto final, puede decirle a API Gateway que use el valor de la variable de etapa, http://${stageVariables.url}. Este valor le dice a API Gateway que sustituya su variable de etapa ${} en tiempo de ejecución, según la etapa en la que se esté ejecutando su API. Puede hacer referencia a las variables de etapa de manera similar para especificar un nombre de función de Lambda, una ruta de proxy de servicio de AWS o un ARN de función de AWS en el campo de credenciales.
Referencia: https://docs.aws.amazon.com/apigateway/latest/developerguide/stage-variables.html