티스토리 뷰

1. handler.js

  1. callback() 필드 중 body 의 값 Type은 String 이어야만 함.
  2. 만약 다른 형식을 지정하면 postman 같은 툴에서 502 Internal Server Error 를 만나게 됨.
    module.export.run = (event, context, callback) => {
      return callback(null, {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Credentials': true
        },
        body: event
      });
    };

2. postman 에서 api uri 로 호출

  1. Body > raw > application/json
    {
        “foo": “bar",
        “hello": “world"
    }

3. Response 응답 값 참고

  1. https://docs.aws.amazon.com/ko_kr/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format 문서 중 "이 요청은 백엔드 Lambda 함수에서 반환되는 출력을 포함하는 다음과 같은 응답 페이로드를 생성합니다.” 아래 응답 json 소스코드 블럭 참고.
  2. https://medium.com/sungjunyoung/lambda-proxy-integration-%ED%99%9C%EC%9A%A9-26c957bc0447
    {
      "message": "Hello me!",
      "input": {
        "resource": "/{proxy+}",
        "path": "/hello/world",
        "httpMethod": "POST",
        "headers": {
          "Accept": "*/*",
          "Accept-Encoding": "gzip, deflate",
          "cache-control": "no-cache",
          "CloudFront-Forwarded-Proto": "https",
          "CloudFront-Is-Desktop-Viewer": "true",
          "CloudFront-Is-Mobile-Viewer": "false",
          "CloudFront-Is-SmartTV-Viewer": "false",
          "CloudFront-Is-Tablet-Viewer": "false",
          "CloudFront-Viewer-Country": "US",
          "Content-Type": "application/json",
          "headerName": "headerValue",
          "Host": "alpha1234.execute-api.us-east-1.amazonaws.com",
          "Postman-Token": "alpha1234-ed83-4a38-aef3-alpha1234",
          "User-Agent": "PostmanRuntime/2.4.5",
          "Via": "1.1 alpha1234.cloudfront.net (CloudFront)",
          "X-Amz-Cf-Id": "pn-alpha1234==",
          "X-Forwarded-For": "192.240.195.186, 192.182.214.183",
          "X-Forwarded-Port": "443",
          "X-Forwarded-Proto": "https"
        },
        "multiValueHeaders":{
          'Accept':[
            "*/*"
          ],
          'Accept-Encoding':[
            "gzip, deflate"
          ],
          'cache-control':[
            "no-cache"
          ],
          'CloudFront-Forwarded-Proto':[
            "https"
          ],
          'CloudFront-Is-Desktop-Viewer':[
            "true"
          ],
          'CloudFront-Is-Mobile-Viewer':[
            "false"
          ],
          'CloudFront-Is-SmartTV-Viewer':[
            "false"
          ],
          'CloudFront-Is-Tablet-Viewer':[
            "false"
          ],
          'CloudFront-Viewer-Country':[
            "US"
          ],
          '':[
            ""
          ],
          'Content-Type':[
            "application/json"
          ],
          'headerName':[
            "headerValue"
          ],
          'Host':[
            "alpha1234.execute-api.us-east-1.amazonaws.com"
          ],
          'Postman-Token':[
            "alpha1234-ed83-4a38-aef3-alpha1234"
          ],
          'User-Agent':[
            "PostmanRuntime/2.4.5"
          ],
          'Via':[
            "1.1 alpha1234.cloudfront.net (CloudFront)"
          ],
          'X-Amz-Cf-Id':[
            "pn-alpha1234=="
          ],
          'X-Forwarded-For':[
            "192.240.196.186, 192.182.214.83"
          ],
          'X-Forwarded-Port':[
            "443"
          ],
          'X-Forwarded-Proto':[
            "https"
          ]
        },
        "queryStringParameters": {
          "name": "me",
          "multivalueName": "me"
        },
        "multiValueQueryStringParameters":{
          "name":[
            "me"
          ],
          "multivalueName":[
            "you",
            "me"
          ]
        },
        "pathParameters": {
          "proxy": "hello/world"
        },
        "stageVariables": {
          "stageVariableName": "stageVariableValue"
        },
        "requestContext": {
          "accountId": "12345678912",
          "resourceId": "roa9yj",
          "stage": "testStage",
          "requestId": "alpha1234-7910-11e6-8f14-alpha1234",
          "identity": {
            "cognitoIdentityPoolId": null,
            "accountId": null,
            "cognitoIdentityId": null,
            "caller": null,
            "apiKey": null,
            "sourceIp": "192.168.196.186",
            "cognitoAuthenticationType": null,
            "cognitoAuthenticationProvider": null,
            "userArn": null,
            "userAgent": "PostmanRuntime/2.4.5",
            "user": null
          },
          "resourcePath": "/{proxy+}",
          "httpMethod": "POST",
          "apiId": "yj415numeric"
        },
        "body": "{\n\t\”foo\": \”bar\",\n\t\”hello\": \”world\"\n}",
        "isBase64Encoded": false
      }
    }

4. 콘솔 serverless 명령시 입력값 파일 event.json

  1. event.json 형식 = https://docs.aws.amazon.com/ko_kr/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
  2. 위 postman 의 Response 와 event.json 형식을 참고하여 event.json 파일 생성.
    {
      "path": "/v1/auth/signup/social-email",
      "httpMethod": "POST",
      "headers": {
        "authorizationToken": "allow",
        "locale": "ko"
      },
      "queryStringParameters": null,
      "pathParameters": null,
      "requestContext": {
        "resourceId": "yz5kw",
        "authorizer": {
          "principalId": "alphanumeric",
          "integrationLatency": 154,
          "exp": "1354041235",
          "iat": "1353951235"
        }
      },
      "body": "{\n\t\”foo\": \”bar\",\n\t\”hello\": \”world\"\n}"
    }

5. 이제, 콘솔에서 serverless 명령으로 로컬에서 디버깅 가능

$ sls invoke local -f [function name] -p event.json —log

6. event.json 완성도 높이기

소스에서 입력값 필드때문에 오류가 나면 event.json 에 항목을 추가하거나 정리하며 완성도 높이기.

7. console.log(...) 로 응답 확인

이제부터 콘솔 serverless 명령으로 함수 호출시 handler.js 에서 console.log(…) 로 Response 확인 가능.

8. Webstorm 설정시 debugger 사용 가능

  1. https://blog.pythian.com/locally-debug-serverless-function/ 
  2. 오른쪽 위 실행 선택상자 > Edit Configurations... 버튼 클릭 후 Node.js 선택
  3. Node parameters: /usr/local/bin/sls invoke local -f [function name] -p event.json
  4. 디버깅 해야 할 부분에 Break point 지정 (단축키 Cmd + F8)
  5. 디버깅 버튼 클릭 (단축키: ^d)

Reference

 

Amazon API Gateway Lambda 권한 부여자에 대한 입력 - Amazon API Gateway

Amazon API Gateway Lambda 권한 부여자에 대한 입력 TOKEN 유형 Lambda 권한 부여자(이전에는 사용자 지정 권한 부여자라고 함)의 경우 API에 대해 권한 부여자를 구성할 때 사용자 지정 헤더를 토큰 원본(Token Source)으로 지정해야 합니다. API 클라이언트가 수신되는 요청에서 필요한 인증 토큰을 전달해야 합니다. 메서드 요청을 수신하면 는 사용자 지정 헤더로부터 토큰을 추출합니다. 그런 다음 토큰을 Lambda 함수

docs.aws.amazon.com

 

API Gateway에서 Lambda 프록시 통합 설정 - Amazon API Gateway

API Gateway에서 Lambda 프록시 통합 설정 API Gateway Lambda 프록시 통합 이해 Amazon API Gateway Lambda 프록시 통합은 단일 API 메서드의 설정을 통해 API를 구축하기 위한 간단하고 강력하며 민첩한 메커니즘입니다. Lambda 프록시 통합을 사용하면 클라이언트가 백엔드에서 단일 Lambda 함수를 호출할 수 있습니다. 이 함수는 다른 Lambda 함수를 호출하는 등 다른 AWS 서비스의 많은 리소스 또는

docs.aws.amazon.com

 

Locally debug your serverless function | Official Pythian® Blog

Serverless architecture opens up an exciting new space for building cloud native and event-driven applications. But this new approach raises new questions..

blog.pythian.com

 

댓글