All files / web/bundles/pimui/js/fetcher base-fetcher.js

94% Statements 47/50
87.5% Branches 28/32
100% Functions 16/16
94% Lines 47/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180      1183x 1183x               33708x 33708x 33708x                 9724x 1438x       1438x         9724x                 1051x 1051x 1014x     1014x     37x     1051x                       14393x   14393x 3150x   3150x 3019x     3009x   1x   1x     131x 131x 131x 131x             3150x     14393x                     3469x 3469x 1534x     1935x 1935x 959x     976x             969x 4610x     969x                         534x                 933x                 23146x 550x   22596x 22596x                       1928x 1928x          
/* global console */
'use strict';
 
define(['jquery', 'underscore', 'backbone', 'routing'], function ($, _, Backbone, Routing) {
    return Backbone.Model.extend({
        entityListPromise: null,
        entityPromises: {},
 
        /**
         * @param {Object} options
         */
        initialize: function (options) {
            this.entityListPromise = null;
            this.entityPromises = {};
            this.options = options || {};
        },
 
        /**
         * Fetch all elements of the collection
         *
         * @return {Promise}
         */
        fetchAll: function (searchOptions) {
            if (!this.entityListPromise) {
                Iif (!_.has(this.options.urls, 'list')) {
                    return $.Deferred().reject().promise();
                }
 
                this.entityListPromise = $.getJSON(
                    Routing.generate(this.options.urls.list, searchOptions),
                ).then(_.identity).promise();
            }
 
            return this.entityListPromise;
        },
 
        /**
         * Search elements of the collection
         *
         * @return {Promise}
         */
        search: function (searchOptions) {
            var url = '';
            if (!_.has(this.options.urls, 'search')) {
                Iif (!_.has(this.options.urls, 'list')) {
                    return $.Deferred().reject().promise();
                } else {
                    url = this.options.urls.list;
                }
            } else {
                url = this.options.urls.search;
            }
 
            return this.getJSON(url, searchOptions).then(_.identity).promise();
        },
 
        /**
         * Fetch an element based on its identifier
         *
         * @param {string} identifier
         * @param {Object} options
         *
         * @return {Promise}
         */
        fetch: function (identifier, options) {
            options = options || {};
 
            if (!(identifier in this.entityPromises) || false === options.cached) {
                var deferred = $.Deferred();
 
                if (this.options.urls.get && !options.force_list_method) {
                    $.getJSON(
                        Routing.generate(this.options.urls.get, _.extend({identifier: identifier}, options))
                    ).then(_.identity).done(function (entity) {
                        deferred.resolve(entity);
                    }).fail(function (promise, status, error) {
                        console.error('Error during fetching: ', error);
 
                        return deferred.reject(promise);
                    });
                } else {
                    this.fetchAll().done(function (entities) {
                        var entity = _.findWhere(entities, {code: identifier});
                        Eif (entity) {
                            deferred.resolve(entity);
                        } else {
                            deferred.reject();
                        }
                    });
                }
 
                this.entityPromises[identifier] = deferred.promise();
            }
 
            return this.entityPromises[identifier];
        },
 
        /**
         * Fetch all entities for the given identifiers
         *
         * @param {Array} identifiers
         *
         * @return {Promise}
         */
        fetchByIdentifiers: function (identifiers, options) {
            options = options || {};
            if (0 === identifiers.length) {
                return $.Deferred().resolve([]).promise();
            }
 
            var uncachedIdentifiers = _.difference(identifiers, _.keys(this.entityPromises));
            if (0 === uncachedIdentifiers.length) {
                return this.getObjects(_.pick(this.entityPromises, identifiers));
            }
 
            return $.when(
                this.getJSON(
                    this.options.urls.list,
                    _.extend({identifiers: uncachedIdentifiers.join(',')}, options)
                ).then(_.identity),
                this.getIdentifierField()
            ).then(function (entities, identifierCode) {
                _.each(entities, function (entity) {
                    this.entityPromises[entity[identifierCode]] = $.Deferred().resolve(entity).promise();
                }.bind(this));
 
                return this.getObjects(_.pick(this.entityPromises, identifiers));
            }.bind(this));
        },
 
        /**
         * Get the list of elements in JSON format.
         *
         * @param {string} url
         * @param {Object} parameters
         *
         * @returns {Promise}
         */
        getJSON: function (url, parameters) {
            return $.getJSON(Routing.generate(url, parameters));
        },
 
        /**
         * Get the identifier attribute of the collection
         *
         * @return {Promise}
         */
        getIdentifierField: function () {
            return $.Deferred().resolve('code');
        },
 
        /**
         * Clear cache of the fetcher
         *
         * @param {string|null} identifier
         */
        clear: function (identifier) {
            if (identifier) {
                delete this.entityPromises[identifier];
            } else {
                this.entityListPromise = null;
                this.entityPromises = {};
            }
        },
 
        /**
         * Wait for promises to resolve and return the promises results wrapped in a Promise
         *
         * @param {Array|Object} promises
         *
         * @return {Promise}
         */
        getObjects: function (promises) {
            return $.when.apply($, _.toArray(promises)).then(function () {
                return 0 !== arguments.length ? _.toArray(arguments) : [];
            });
        }
    });
});