Skip to content

Instantly share code, notes, and snippets.

@rik
Created February 16, 2015 21:30
Show Gist options
  • Save rik/8c60533b9fc0a4da3d6c to your computer and use it in GitHub Desktop.
Save rik/8c60533b9fc0a4da3d6c to your computer and use it in GitHub Desktop.

Revisions

  1. rik created this gist Feb 16, 2015.
    40 changes: 40 additions & 0 deletions gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    ensure_endpoint: function() {
    if (!navigator.push) {
    // Do nothing when push notifications are not supported
    console.log('no support for push notifications');
    return Promise.resolve();
    }

    if (ensure_endpoint_in_progress) {
    return Promise.resolve();
    }
    ensure_endpoint_in_progress = true;

    function ensure_endpoint_done() {
    ensure_endpoint_in_progress = false;
    }

    return asyncStorage.getItem(ENDPOINT_ID_KEY).then(function(endpoint) {
    if (endpoint) {
    return Promise.resolve();
    }

    var defer = Utils.defer();
    var req = navigator.push.register();
    req.onsuccess = function() {
    defer.resolve(req.result);
    };
    req.onerror = function() {
    defer.reject();
    };

    return defer.promise.then(function(endpoint_url) {
    var set_promise = asyncStorage.setItem(ENDPOINT_ID_KEY, endpoint_url);
    return Promise.all([endpoint_url, set_promise]);
    }).then(function(endpoint_url) {
    return SumoDB.register_push_endpoint(endpoint_url);
    }).catch(function() {
    return asyncStorage.removeItem(ENDPOINT_ID_KEY);
    });
    }).then(ensure_endpoint_done, ensure_endpoint_done);
    },