3

I'm trying to return jsonp as in callbackname(data.strified)

callback( null, 
    ( !!event.cb && event.cb.length > 0 ) 
    ? event.cb.replace( /[^a-z0-9_]/i, '' ) + '(' + JSON.stringify( data ) + ')'
    : data
);

My quick and dirty way now returns the data and if ?cb=test is given it returns:

"test({\"valid\":false,\"data\":false})"

Is there anyway to get rid of the quotes and escape characters? The API should work with and without callback set.

Toby
  • 2,650
  • 5
  • 28
  • 44

3 Answers3

5

Given that you have this type of lambda function:

exports.handler = function(event, context) {
    var data={"test":"data"};
    context.done( null, 
            ( !!event.cb && event.cb.length > 0 ) 
            ? event.cb.replace( /[^a-z0-9_]/i, '' ) + '(' + JSON.stringify( data ) + ')'
            : data
    );
};

When you give it an event like

{
  "cb": "callback"
}

It will give this output:

"callback({\"test\":\"data\"})"

So far, so good. Now you come to API Gateway and in Integration Response part you write this

$util.parseJson($input.json('$'))

Than you will get callback({"test":"data"}) as output when you invoke the API Gateway endpoint.

Çağatay Gürtürk
  • 6,901
  • 3
  • 31
  • 44
1

You can use an integration mapping template to do this. Something like this should help you to parse the Json.

$util.parseJson($input.json('$'))

Here are more details about mapping templates.

Balaji
  • 970
  • 7
  • 12
  • how would I set up the integration mapping template? I kinda already did the above but it now outputs nothing... also would that support json and jsonp? as in pure data vs data wrapped in function name – Toby May 28 '16 at 21:57
1

As Çağatay Gürtürk pointed out, you stringify your result and return it.

However, if your lambda also accepts non callbacks, you can check in the VTL template:

API Gateway and in Integration Response part:

#if($input.params('callback') != "")
$util.parseJson($input.json('$'))
#else
$input.json('$')
#end
Teebu
  • 451
  • 5
  • 12