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

Access to a resource with an end slash #25

Open pirhoo opened 11 years ago

pirhoo commented 11 years ago

Hi folks,

The module is great but I found a little issue with endpoints terminating by a slash.

Not works:

site.v1.resource["1"].get(console.log) // Fermata dislikes the 501 redirection

Works:

site.v1.resource["1/"].get(console.log) // Note the slash after the identifier 

I didn't find option to add a slash automatically... Any help ?

Cheers,

pirhoo commented 11 years ago

I mad this workaround (using a plugin) :

fermata.registerPlugin("slashed", function (transport, baseURL) {

    this.base = baseURL;                            
    transport = transport.using('statusCheck').using('autoConvert', "application/json");        

    return function (request, callback) {                        
        // If the last caracter of the path isn't a slash
        if( String(request.path[request.path.length - 1]).substr(-1,1) !== "/") {
            // Automatically adding a tail slash to the URL's end
            request.path[request.path.length - 1] += "/";
            // It's also possible to add an empty string
            // request.path.push("");
        }

        transport(request, callback);
    };
});

var site = fermata.slashed("http://api.example.org");
site.v1.instance["1"].get(console.log); // Works !
site.v1.instance["1/"].get(console.log); // Works too !
natevw commented 11 years ago

Cool, glad you were able to get a plugin working for this — I probably don't promote this enough in the docs, but plugins are intended to be lightweight enough to make one for every site whenever desirable.

There's two ways you could get a slash at the end of a URL right now, by avoiding escaping with an array (site.v1.resource(["1/"])) or by appending a blank component (site.v1.resource['']).

I'll leave this open for now in case there's any good clean general solutions, but a plugin might be the most appropriate solution in this sort of situation.