CPAN-API/cpan-api — pull request #159 by grantm (2012-02-08 02:16:04+00:00)
Title: Allow non-JSON content (e.g.: POD) to be delivered via JSONP (includes tests)

Without this patch, a JSONP request like http://api.metacpan.org/pod/Acme::Orange?callback=my_func would result in the Javascript function wrapper being applied to the text/plain or text/html body - resulting in invalid Javascript.

This patch takes the text body and encodes it as a string in a JSON object before the JSONP callback function wrapper is added. The object key name is determined from the original content type so as request for POD as HTML will return something like:

foo({ "html" : "..."});

Unlike my earlier pull request, this time I've included regression tests to confirm that the JSONP wrapping is working as expected and that the data can be decoded successfully.

Adding the tests revealed a pre-existing bug - 404 requests like http://api.metacpan.org/pod/No::Such::Module?callback=foo were getting the callback function wrapper added twice (resulting in 'foo(foo(...););'). I've added a fix that skips adding the function wrapper if the response 'Content-type' is already 'text/javascript'.