18

I am using AWS Lambda to create a fetch API by passing a query parameter eg. vendorId, but in some case, I need whole data without passing the query parameter and in that case, my code is broken. Let me know how I can handle the query parameter.

  var mysql=require('mysql'); //Require whatever connector you need.

  function getConnection()
   {
        var params={
           host     : 'myhostinfo',
           user     : 'myuser',
            password : 'mypwd',
           database : 'mydb'
    };

return mysql.createConnection(params);
}
      //This is your handler.
     exports.handler=function(event, context,callback)
    {

 //This is declared inside the handler: it is guaranteed to never be reused!.
   var connection=getConnection();
var fetchvendors="";


if(event.query.vendorid)
{   
    var vendorid=parseInt(event.query.vendorid);
    fetchvendors="SELECT v.*,c.vcategoryname FROM `tbl_vendors` v LEFT 
 OUTER JOIN tbl_demo_categories c ON v.vendorcatid=c.vcategoryid WHERE 
  v.vendorid="+vendorid;
}

else{
       fetchvendors="SELECT v.*,c.vcategoryname FROM `tbl_vendors` v LEFT 
OUTER JOIN tbl_demo_categories c ON v.vendorcatid=c.vcategoryid WHERE 
 status=1";
}
     connection.query(fetchvendors, function (error, results, fields) {
          if (error) {
            connection.destroy();
             throw error;
          } else {
              // connected!
             callback(null, results);
             connection.end();
        }
     });
  }

here is the result

          Response:
        {
              "errorMessage": "RequestId: 42fd18b1-598c-4f7e-b93b- 
                b146777772b2 
            Process exited before completing request"
               }

          Request ID:
              "42fd18b1-598c-4f7e-b93b-b146777772b2"

             Function Logs:
            START RequestId: 42fd18b1-598c-4f7e-b93b-b146777772b2 Version: 
        $LATEST
             2019-04-04T10:48:34.959Z   42fd18b1-598c-4f7e-b93b- 
          b146777772b2  TypeError: Cannot read property 'vendorid' of 
                       undefined
0

5 Answers 5

29

If you are using API Gateway as the trigger to the lambda function, the query paramters are available at event.queryStringParameters. So you should be doing event.queryStringParameters.vendorid if vendorid is the GET param. Here's a full sample of API Gateway Proxy request to Lambda.

{
  "body": "eyP0ZXQ0IjoiYm9keSJ9",
  "resource": "/{proxy+}",
  "path": "/path/to/resource",
  "httpMethod": "POST",
  "isBase64Encoded": true,
  "queryStringParameters": {
    "foo": "bar"
  },
  "pathParameters": {
    "proxy": "/path/to/resource"
  },
  "stageVariables": {
    "baz": "qux"
  },
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate, sdch",
    "Accept-Language": "en-US,en;q=0.8",
    "Cache-Control": "max-age=0",
    "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",
    "Host": "1234567890.execute-api.us-east-1.amazonaws.com",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Custom User Agent String",
    "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
    "X-Amz-Cf-Id": "cDehZQoZnx43VYQb9j2-naCh-9y396Uhbp027Y2JvkCPNLmGJHqlaA==",
    "X-Forwarded-For": "127.0.0.1, 127.0.0.2",
    "X-Forwarded-Port": "443",
    "X-Forwarded-Proto": "https"
  },
  "requestContext": {
    "accountId": "123456789012",
    "resourceId": "123456",
    "stage": "prod",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
    "requestTime": "09/Apr/2015:12:34:56 +0000",
    "requestTimeEpoch": 1428582896000,
    "identity": {
      "cognitoIdentityPoolId": null,
      "accountId": null,
      "cognitoIdentityId": null,
      "caller": null,
      "accessKey": null,
      "sourceIp": "127.0.0.1",
      "cognitoAuthenticationType": null,
      "cognitoAuthenticationProvider": null,
      "userArn": null,
      "userAgent": "Custom User Agent String",
      "user": null
    },
    "path": "/prod/path/to/resource",
    "resourcePath": "/{proxy+}",
    "httpMethod": "POST",
    "apiId": "1234567890",
    "protocol": "HTTP/1.1"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

9

you should put pre-check for existence of object and its keys like this :

if(event && event.query && event.query.vendorid)

3 Comments

Thanks for the reply, Sorry to say the problem is still the same.
after trying above solution now what error you are getting ? Please share error.
it solved my issue as there was something wrong in my code as in my string template I'm using param instead of a query. Thanks a lot
6

Try this -

event.queryStringParameters.pincode

Comments

3

I know this one is old but for me it worked when I used the following

event.queryStringParameters?.vendorid

Notice ?. operator because queryStringParameters may not exist in the query string

2 Comments

The ?. operator is actually because event.queryStringParameters may not exist.
@GreenGrassoHolm true
0

You can use

import middy from "@middy/core";
import httpEventNormalizer from "@middy/http-event-normalizer";

middy(handler).use([
  httpEventNormalizer()
])

then get query from event.queryStringParameters?.queryParameterName

middy will remove query parameters if their value is null from queryStringParameters

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.