All files / dist Store.js

33.64% Statements 37/110
23.81% Branches 20/84
21.74% Functions 5/23
34% Lines 34/100
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 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255  1x 1x     1x 1x 1x 1x     1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x                                               1x                               1x                                                       1x                                                   1x             1x                         1x                       1x                             1x                                                           1x                                                                 1x       1x                 1x               1x 1x     1x  
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    Iif (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) Eif (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var mobx_1 = require("mobx");
var NetworkStore_1 = require("./NetworkStore");
var NetworkUtils_1 = require("./NetworkUtils");
var Record_1 = require("./Record");
var utils_1 = require("./utils");
var Store = (function (_super) {
    __extends(Store, _super);
    function Store() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        /**
         * Cache async actions (can be overriden with force=true)
         *
         * @private
         *
         * @memberOf Store
         */
        _this.__cache = {
            fetch: {},
            fetchAll: {},
        };
        return _this;
    }
    /**
     * Import the JSON API data into the store
     *
     * @param {IJsonApiResponse} body - JSON API response
     * @returns {(IModel|Array<IModel>)} - Models parsed from body.data
     *
     * @memberOf Store
     */
    Store.prototype.sync = function (body) {
        var data = this.__iterateEntries(body, this.__addRecord.bind(this));
        this.__iterateEntries(body, this.__updateRelationships.bind(this));
        return data;
    };
    /**
     * Fetch the records with the given type and id
     *
     * @param {string} type Record type
     * @param {number|string} type Record id
     * @param {boolean} [force] Force fetch (currently not used)
     * @param {IRequestOptions} [options] Server options
     * @returns {Promise<Response>} Resolves with the Response object or rejects with an error
     *
     * @memberOf Store
     */
    Store.prototype.fetch = function (type, id, force, options) {
        var _this = this;
        var query = this.__prepareQuery(type, id, null, options);
        if (!this.static.cache) {
            return this.__doFetch(query, options);
        }
        this.__cache.fetch[type] = this.__cache.fetch[type] || {};
        // TODO: Should we fake the cache if the record already exists?
        if (force || !(query.url in this.__cache.fetch[type])) {
            this.__cache.fetch[type][query.url] = this.__doFetch(query, options)
                .catch(function (e) {
                // Don't cache if there was an error
                delete _this.__cache.fetch[type][query.url];
                throw e;
            });
        }
        return this.__cache.fetch[type][query.url];
    };
    /**
     * Fetch the first page of records of the given type
     *
     * @param {string} type Record type
     * @param {boolean} [force] Force fetch (currently not used)
     * @param {IRequestOptions} [options] Server options
     * @returns {Promise<Response>} Resolves with the Response object or rejects with an error
     *
     * @memberOf Store
     */
    Store.prototype.fetchAll = function (type, force, options) {
        var _this = this;
        var query = this.__prepareQuery(type, null, null, options);
        if (!this.static.cache) {
            return this.__doFetch(query, options);
        }
        if (force || !(query.url in this.__cache.fetchAll)) {
            this.__cache.fetchAll[query.url] = this.__doFetch(query, options)
                .catch(function (e) {
                // Don't cache if there was an error
                delete _this.__cache.fetchAll[query.url];
                throw e;
            });
        }
        return this.__cache.fetchAll[query.url];
    };
    /**
     * Destroy a record (API & store)
     *
     * @param {string} type Record type
     * @param {(number|string)} id Record id
     * @param {IRequestOptions} [options] Server options
     * @returns {Promise<boolean>} Resolves true or rejects with an error
     *
     * @memberOf Store
     */
    Store.prototype.destroy = function (type, id, options) {
        var model = this.find(type, id);
        if (model) {
            return model.remove(options);
        }
        return Promise.resolve(true);
    };
    Store.prototype.request = function (url, method, data, options) {
        if (method === void 0) { method = 'GET'; }
        return NetworkUtils_1.fetch({ url: this.__prefixUrl(url), options: options, data: data, method: method, store: this });
    };
    /**
     * Make the request and handle the errors
     *
     * @param {IQueryParams} query Request query info
     * @param {IRequestOptions} [options] Server options
     * @returns {Promise<Response>} Resolves with the Response object or rejects with an error
     *
     * @memberof Store
     */
    Store.prototype.__doFetch = function (query, options) {
        return NetworkUtils_1.read(this, query.url, query.headers, options).then(this.__handleErrors);
    };
    /**
     * Function used to handle response errors
     *
     * @private
     * @param {Response} response API response
     * @returns API response
     *
     * @memberOf Store
     */
    Store.prototype.__handleErrors = function (response) {
        if (response.error) {
            throw response.error;
        }
        return response;
    };
    /**
     * Add a new JSON API record to the store
     *
     * @private
     * @param {IJsonApiRecord} obj - Object to be added
     * @returns {IModel}
     *
     * @memberOf Store
     */
    Store.prototype.__addRecord = function (obj) {
        var type = obj.type, id = obj.id;
        var record = this.find(type, id);
        var flattened = utils_1.flattenRecord(obj);
        if (record) {
            record.update(flattened);
        }
        else if (this.static.types.filter(function (item) { return item.type === obj.type; }).length) {
            record = this.add(flattened, obj.type);
        }
        else {
            record = new Record_1.Record(flattened);
            this.add(record);
        }
        // In case a record is not a real record
        // TODO: Figure out when this happens and try to handle it better
        if (record && typeof record.setPersisted === 'function') {
            record.setPersisted(true);
        }
        return record;
    };
    /**
     * Update the relationships between models
     *
     * @private
     * @param {IJsonApiRecord} obj - Object to be updated
     * @returns {void}
     *
     * @memberOf Store
     */
    Store.prototype.__updateRelationships = function (obj) {
        var _this = this;
        var record = this.find(obj.type, obj.id);
        if (!record) {
            return;
        }
        var refs = obj.relationships ? Object.keys(obj.relationships) : [];
        refs.forEach(function (ref) {
            var items = obj.relationships[ref].data;
            if (items instanceof Array && items.length < 1) {
                // it's only possible to update items with one ore more refs. Early exit
                return;
            }
            if (items) {
                var models = utils_1.mapItems(items, function (_a) {
                    var id = _a.id, type = _a.type;
                    return _this.find(type, id) || id;
                });
                var type = items instanceof Array ? items[0].type : items.type;
                record.assignRef(ref, models, type);
            }
        });
    };
    /**
     * Iterate trough JSON API response models
     *
     * @private
     * @param {IJsonApiResponse} body - JSON API response
     * @param {Function} fn - Function to call for every instance
     * @returns
     *
     * @memberOf Store
     */
    Store.prototype.__iterateEntries = function (body, fn) {
        utils_1.mapItems((body && body.included) || [], fn);
        return utils_1.mapItems((body && body.data) || [], fn);
    };
    return Store;
}(NetworkStore_1.NetworkStore));
/**
 * List of Models that will be used in the collection
 *
 * @static
 *
 * @memberOf Store
 */
Store.types = [Record_1.Record];
/**
 * Should the cache be used for API calls when possible
 *
 * @static
 *
 * @memberof Store
 */
Store.cache = true;
__decorate([
    mobx_1.action
], Store.prototype, "sync", null);
exports.Store = Store;