natevw / fermata

Succinct native REST client, for client-side web apps and node.js. Turns URLs into (optionally: magic!) JavaScript objects.
328 stars 24 forks source link

Simplify API by not having user choose json or raw plugin upfront #11

Closed Pyrolistical closed 12 years ago

Pyrolistical commented 13 years ago

Instead of forcing the user to choose fermata.json(..) or fermata.raw(..) only decode response body as json only if XMLHttpRequest.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");

natevw commented 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.

Using autoConvert helper plugin

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); });

Only convert JSON

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!