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.

3
  • I've the same question... Do you have any update? Thanks @Tobias! Commented May 26, 2016 at 6:05
  • see answer, I think that's the easiest way. Commented May 28, 2016 at 21:57
  • @IgnacioOcampo you got a solution for it? :) Commented Jul 5, 2016 at 20:14

3 Answers 3

5
+200

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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
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

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.