Closed Pyrolistical closed 12 years ago
Hi @Pyrolistical — sorry for such a late response, the organization's github wasn't configured right for me to get notifications for this repo when you filed.
There's a couple ways you could get this behaviour, mostly dependent on if you're okay with a few other responses types getting automatically converted.
This first will convert any known type (currently only text/plain and application/x-www-form-urlencode, but subject to change) to a non-raw format, and pass the rest through with full header/status/body information:
fermata.registerPlugin('auto', function (transport, baseURL) {
this.base = baseURL;
return transport.using('statusCheck').using('autoConvert');
});
This is just like the JSON plugin except that it doesn't force a default content type for the auto-conversion filter. Depending on the API you're talking to, you may need to encourage a JSON response by preferring it in an Accept header:
fermata.auto("http://example.com").get({'Accept':"application/json,*/*;q=0.9"}, null, function (e,d) { console.log(e,d); });
This plugin more exactly implements the behaviour you describe above:
fermata.registerPlugin('jsonOrRaw', function (transport, baseURL) {
this.base = baseURL;
transport = transport.using('statusCheck');
return function (request, callback) {
transport(request, function (err, response) {
if (response.headers['Content-Type'] === "application/json") {
try {
response = JSON.parse(response.data);
} catch (e) {
err || (err = e);
}
}
callback(err, response);
});
}
});
Hope this helps!
Instead of forcing the user to choose
fermata.json(..)
orfermata.raw(..)
only decode response body as json only ifXMLHttpRequest.getResponseHeader("Content-Type") == "application/json"
. Otherwise return response body as raw.You can then have a new static constructor
var site = fermata("http://youraccount.example.com");