2
\$\begingroup\$

I was recently in a situation where I had to use vanilla js (no es6 and no http libraries, so I came up with this simple wrapper for get calls :

var Http = (function() {
    function Http() {
        this.xhr = new XMLHttpRequest();
    }
    Http.prototype.get = function(url, onload) {
        this.xhr.onreadystatechange = function() {
            if (this.readyState === 4 && this.status == 200) {
                onload(this.responseText);
            }
        }
        this.xhr.open("GET", url);  
        this.xhr.send();
    }
    return Http;
})()

And I would use it like this :

var http = new Http();
http.get('endpoint', function() {});

Can you see any potential problems with this approach like memory leaks insecurities etc. and would you and if possible, how, add something to improve it, like ability to handle multiple get() in row from the same http object?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

I am concerned that you have added a layer of false generalization around a very specific, usually one-time use, request object. I would think the class would be better named Request or similar to better clarify what this wrapper represents as currently stands.

If your intent is to truly define a class that provides generalized request functionality ( get, post, put, etc.) then you should think more closely about how (and if) the class holds state for individual request objects. You probably would not store a common request object for every request on ‘this’, but rather would create a new request object for every method call. If you find yourself no longer holding request state in your class, then you then would probably consider whether and instantiable class is really what you want.

On a different front, your current code really does nothing to handle errors in the request. If you are spending the time to build a common request abstraction like this, you should add appropriate error handling.

Finally, if you are in the business of building a new request abstraction, then I would strongly consider building of the much more modern and now widely supported Fetch API.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.