Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a javascript client-side library for queuing ajax requests with storage support

I'm looking for a javascript client side lib to handle an ajax or websocket requests queue like this :

  • directly transmit request when user is online and the server is up
  • store requests when user is offline or server is down using local storage
  • send stored requests when user is online and server is back online

Ideally :

  • without jquery
  • I'm also looking for a serverside component to go along

I can't find anything like this. Should I build one myself using localstorage, window.navigator.onLine and socket.io for instance or is there already some lib for that purpose ?

Thanks.

like image 929
sylvain Avatar asked Sep 09 '13 15:09

sylvain


1 Answers

The question is probably going to be closed, since asking for a library is usually not welcomed on StackOverflow. However, this is a fun little challenge. (Took me ~15 minutes to complete.)

This is actually not a very big task to handle, barely 50 lines or so. That's probably why you can't find a small library doing this.

function Sender() {
    var requests = [],
        state = 0; // 0 = closed, 1 = open
        ws = new WebSocket();

    ws.onopen = function() {
        state = 1;
        if (requests.length) {
            send();
        }
    };

    ws.onerror = function() {
        if (ws.readyState !== 1) { // 1 is "OPEN"
            close();
        }
    };

    // Let's fill in the requests array if necessary
    // IIFE because I don't want to pollute the scope with `req`
    (function() {
        var req = JSON.parse(localStorage.get('queue'));
        if (req.length) {
            requests = requests.concat(req);
        }
    }());

    return {
        send: function(msg) {
            if (state === 0) {
                requests.push(msg);
            }
            else {
                send();
            }
        },
        close: function() {
            state = 0;
            localStorage.set('queue', JSON.stringify(requests));
        }
    };

    function send() {
        var done = false;
        while (!done) {
            if (state === 1) {
                ws.send(requests.pop());
                if (!requests.length) {
                    done = true;
                }
            }
            else {
                done = true;
            }
        }
    }
}

// Usage example
var sender = Sender();
sender.send('message');

// let's say your "disconnect" button is in a variable
disconnect.addEventListener('click', function() {
    sender.close();
}, false);

The server doesn't have to handle anything except normal requests. If you want, you can add a timestamp to the message you send, this way it's quite easy (2 lines or so) to keep track of the time.

like image 170
Florian Margaine Avatar answered Oct 29 '22 16:10

Florian Margaine