AWS Lambda, API Gateway, Node - GET, POST, PUT.. 요청의 쿼리 매개변수에 쉽게 액세스하는 방법.

14671 단어 serverlessawslamdanode

게시물의 비디오 버전





아래는 게시물의 텍스트 버전입니다.

문제 - 길고 복잡한 "이벤트" 객체가 API Gateway에서 제공됩니다.



새 Lamda 함수를 만들 때 기본 코드는 다음과 같습니다.

exports.handler = async (event) => {
    // AWS gives you this "event" as a parameter.
};


"event"매개변수에는 HTTP 요청에 대한 모든 세부 정보가 있어야 합니다. 그러나 "event"개체는 길고 신경쓰지 않는 내용이 많습니다.

다음은 GET 요청(HTTP API 버전 2 포함)에 대한 샘플 이벤트 개체입니다.

{
    "version": "2.0",
    "routeKey": "ANY /http_api_post_test",
    "rawPath": "/default/http_api_post_test",
    "rawQueryString": "first_name=Khoj",
    "headers": {
        "accept": "*/*",
        "accept-encoding": "gzip, deflate, br",
        "cache-control": "no-cache",
        "content-length": "0",
        "host": "he4vxo0r3j.execute-api.ap-south-1.amazonaws.com",
        "postman-token": "9d390677-0e57-4060-9040-850e94a5c964",
        "user-agent": "PostmanRuntime/7.26.8",
        "x-amzn-trace-id": "Root=1-608cd65c-3c8c34f603f20b100a7449d4",
        "x-forwarded-for": "106.220.136.5",
        "x-forwarded-port": "443",
        "x-forwarded-proto": "https"
    },
    "queryStringParameters": {
        "first_name": "Khoj"
    },
    "requestContext": {
        "accountId": "941626753563",
        "apiId": "he4vxo0r3j",
        "domainName": "he4vxo0r3j.execute-api.ap-south-1.amazonaws.com",
        "domainPrefix": "he4vxo0r3j",
        "http": {
            "method": "GET",
            "path": "/default/http_api_post_test",
            "protocol": "HTTP/1.1",
            "sourceIp": "106.220.136.5",
            "userAgent": "PostmanRuntime/7.26.8"
        },
        "requestId": "eoZuigwtBcwEPKg=",
        "routeKey": "ANY /http_api_post_test",
        "stage": "default",
        "time": "01/May/2021:04:17:32 +0000",
        "timeEpoch": 1619842652981
    },
    "isBase64Encoded": false
}


솔루션 - 이를 위한 NPM 패키지가 있습니다(제가 만들었습니다)



여기 링크가 있습니다: https://www.npmjs.com/package/lamda-api-gateway-event-parser

이 패키지를 사용하면 이벤트 개체에서 매개변수를 쉽고 균일하게 추출할 수 있습니다.

패키지는 다음 유형의 HTTP 이벤트/요청을 처리합니다.
  • 쿼리 문자열 매개변수가 있는 단순 GET 요청
  • application/x-www-form-urlencoded 양식 데이터가 있는 POST, PUT, PATCH, DELETE 요청.
  • 다중 파트/양식 데이터 양식 데이터가 있는 POST, PUT, PATCH, DELETE 요청.
  • HTTP 요청의 JSON 본문
  • HTTP 요청의 XML 본문

  • 출력으로 얻는 것은 ...



    위의 모든 경우에 아래와 같은 모양의 3~5개의 키가 있는 객체를 출력으로 얻습니다.

    {
        userAgent: 'The user agent of the caller (in-case you need that)',
        originalEvent: {}, // the whole original event object, just in-case.
        prams: {}, // A nice neat prams object irrespective of the type of input HTTP event.
        error: 'In case there is an error parsing the XML or JSON, you get an error here.',
        [xmlString / jsonString]: 'The original XML / JSON string in-case you need that and are not happy with the parsing.' 
    }
    


    빠른 시작



    설치하는 방법?



    보통:

    nmp i lamda-api-gateway-event-parser
    yarn add lamda-api-gateway-event-parser
    


    사용하는 방법?



    일반적으로 이벤트 구문 분석은 Lamda 함수에서 가장 먼저 수행하는 작업입니다. 그래서 그냥 그렇게 추가..

    const eventParser = require('lamda-api-gateway-event-parser'); // Bring it in.
    
    exports.handler = async (event) => {
        let niceNeatParsedEvent = eventParser.parse(event); // Parsing the event.
        // All the other awesome things you need to do
    };
    


    파일 업로드 및 multipart/form-data 이벤트 정보



    우리가 받는 이벤트가 multipart/form-data 유형이라면 패키지는 평소와 같이 모든 양식 필드를 추출하고 위에서 설명한 대로 멋진 "params"객체를 만듭니다.

    파일의 경우 파일의 내용이 "tmp"폴더(AWS Lamda에서 제공)에 저장됩니다. "params"개체를 보면 다음과 같습니다.

    params: {
        simple_param_1: "Simple text value",
        file_upload_param_name: {
            type: 'file',
            filename: 'the name of the file',
            contentType: 'content type eg: image/jpeg',
            path: 'file path in lamda environment. eg: "/tmp/cat.jpeg"'
        }
    }
    


    이 부분에 대한 주요 크레딧: https://github.com/myshenin/aws-lambda-multipart-parser. 그러나 repo는 약간 구식이며 더 이상 유지되지 않습니다.

    예상대로 작동하지 않습니까?



    이 패키지에는 2가지 가정이 있습니다(이 가정에 따라 Lambda 함수가 실행되지 않으면 작동하지 않을 수 있음).
  • API 게이트웨이 측에서 HTTP API(REST API 아님)를 사용하고 있습니다. 왜요? 더 빠르고 저렴하기 때문입니다. More info here.
  • API 게이트웨이 버전 2(최신). 이 버전은 버전 1과 다른 "이벤트"개체 구조를 가지고 있습니다. 이 때문에 패키지가 "이벤트 유형"을 식별하고 올바른 구문 분석기를 배포하지 못할 수 있습니다. 이것은 현재 새로운 기능에 대한 AWS의 기본값입니다.
  • 좋은 웹페이지 즐겨찾기