Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
webbingbrasil/core-module / Assets / js / apiServices.js
Size: Mime:
/**
 * Services Object for REST
 * Created by danilo on 15/03/16.
 */
var apiServices;
apiServices = {
    /**
     * Configurable data for authentication in the API
     */
    apiURI: "/api/",
    apiKey: "",

    /**
     * Token used for communication with the API
     */
    apiToken: null,

    init: function () {
        var self = this;

        self.serializeObject();
        self.ajaxPrefilter();

        if (localStorage.getItem('cmsApiToken') !== null) {
            self.apiToken = localStorage.getItem('cmsApiToken');
            return self;
        }

        return this.authenticate().done(function (data) {
            localStorage.setItem('cmsApiToken', data.token);
            self.apiToken = data.token;
        });
    },

    serializeObject: function () {
        $.fn.serializeObject = function () {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
    },

    ajaxPrefilter: function () {
        var self = this;
        $.ajaxPrefilter(function (opts, originalOpts, jqXHR) {
            // you could pass this option in on a "retry" so that it doesn't
            // get all recursive on you.
            if (opts.refreshRequest) {
                return;
            }

            // our own deferred object to handle done/fail callbacks
            var dfd = $.Deferred();

            // if the request works, return normally
            jqXHR.done(dfd.resolve);

            // if the request fails, do something else
            // yet still resolve
            jqXHR.fail(function () {
                var args = Array.prototype.slice.call(arguments);
                if (jqXHR.responseJSON !== undefined && (jqXHR.responseJSON.error == 'token_invalid' || jqXHR.responseJSON.error == 'token_expired')) {
                    self.refreshToken(jqXHR, dfd, originalOpts, args);
                } else {
                    dfd.rejectWith(jqXHR, args);
                }
            });

            // NOW override the jqXHR's promise functions with our deferred
            return dfd.promise(jqXHR);
        });
    },

    ajax: function (uri, method, data, refresh) {
        var self = this;
        var request = {
            url: self.apiURI + uri,
            type: method,
            contentType: "application/json",
            accepts: "application/json",
            refreshRequest: refresh == undefined ? false : refresh,
            cache: false,
            dataType: 'json',
            crossDomain: true,
            data: method.toLowerCase() != 'get' ? JSON.stringify(data) : data
        };
        if (self.apiToken != null) {
            request.beforeSend = function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + self.apiToken);
                xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            }
        }
        return $.ajax(request);
    },

    authenticate: function () {
        var self = this;
        var data = {
            key: self.apiKey
        };
        return self.ajax('authenticate', 'POST', data, false)
    },

    refreshToken: function (jqXHR, dfd, originalOpts, args) {
        var self = this;
        var request = {
            url: self.apiURI + 'authenticate/refresh',
            refreshRequest: true,
            type: 'PUT',
            contentType: "application/json",
            accepts: "application/json",
            dataType: 'json',
            crossDomain: true,
            error: function (res) {
                self.apiToken = null;
                localStorage.removeItem('cmsApiToken');
                // session can't be saved
                // reject with the original 401 data
                dfd.rejectWith(jqXHR, args);
            },
            success: function (res) {
                // retry with a copied originalOpts with refreshRequest.
                var newOpts = $.extend({}, originalOpts, {
                    refreshRequest: false
                });
                self.apiToken = res.token;
                localStorage.setItem('cmsApiToken', res.token);
                // pass this one on to our deferred pass or fail.
                $.ajax(newOpts).then(dfd.resolve, dfd.reject);
            }
        };

        if (self.apiToken != null) {
            request.beforeSend = function (xhr) {
                xhr.setRequestHeader("Authorization",
                    "Bearer " + self.apiToken);
            }
        }

        $.ajax(request);
    }
};