All files Store.ts

100% Statements 91/91
98.04% Branches 50/51
100% Functions 17/17
100% Lines 78/78
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 256 257 258 259 260 261 262 263 264 265 266 267 268 2691x                   1x 1x 1x   1x               82x                 1x                 1x                     82x                         1x 98x 98x 98x                           20x 20x   20x 2x     18x     18x 17x     2x 2x       18x                         41x 41x   41x 2x     39x 39x 38x     5x 5x       39x                         1x 3x 3x 2x   1x     3x 2x     1x 3x 3x 3x 3x                       1x 59x                       1x     52x       52x                       1x 203x 203x 203x   203x 26x 297x 36x   141x 141x           203x 203x     203x                       203x 203x 203x 203x 56x 56x   1x   55x 55x 51x 51x                             1x 196x 196x   1x  
import {action} from 'mobx';
 
import {Collection, IModel} from 'mobx-collection-store';
 
import ICache from './interfaces/ICache';
import IDictionary from './interfaces/IDictionary';
import IHeaders from './interfaces/IHeaders';
import IRequestOptions from './interfaces/IRequestOptions';
import * as JsonApi from './interfaces/JsonApi';
 
import {NetworkStore} from './NetworkStore';
import {fetch, read, remove} from './NetworkUtils';
import {Record} from './Record';
import {Response} from './Response';
import {flattenRecord, mapItems} from './utils';
 
interface IQueryParams {
  url: string;
  data?: object;
  headers: IHeaders;
}
 
export class Store extends NetworkStore {
 
  /**
   * List of Models that will be used in the collection
   *
   * @static
   *
   * @memberOf Store
   */
  public static types = [Record];
 
  /**
   * Should the cache be used for API calls when possible
   *
   * @static
   *
   * @memberof Store
   */
  public static cache = true;
 
  public static: typeof Store;
 
  /**
   * Cache async actions (can be overriden with force=true)
   *
   * @private
   *
   * @memberOf Store
   */
  private __cache: ICache = {
    fetch: {},
    fetchAll: {},
  };
 
  /**
   * 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
   */
  @action public sync(body: JsonApi.IResponse): IModel|Array<IModel> {
    const data: IModel|Array<IModel> = 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
   */
  public fetch(type: string, id: number|string, force?: boolean, options?: IRequestOptions): Promise<Response> {
    const query: IQueryParams = 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((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
   */
  public fetchAll(type: string, force?: boolean, options?: IRequestOptions): Promise<Response> {
    const query: IQueryParams = this.__prepareQuery(type, null, null, options);
 
    if (!this.static.cache) {
      return this.__doFetch(query, options);
    }
 
    this.__cache.fetchAll[type] = this.__cache.fetchAll[type] || {};
    if (force || !(query.url in this.__cache.fetchAll[type])) {
      this.__cache.fetchAll[type][query.url] = this.__doFetch(query, options)
        .catch((e) => {
          // Don't cache if there was an error
          delete this.__cache.fetchAll[type][query.url];
          throw e;
        });
    }
 
    return this.__cache.fetchAll[type][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
   */
  public destroy(type: string, id: number|string, options?: IRequestOptions): Promise<boolean> {
    const model: Record = this.find(type, id) as Record;
    if (model) {
      return model.remove(options);
    }
    return Promise.resolve(true);
  }
 
  public request(url: string, method: string = 'GET', data?: object, options?: IRequestOptions): Promise<Response> {
    return fetch({url: this.__prefixUrl(url), options, data, method, store: this});
  }
 
  public removeAll<T extends IModel>(type: string): Array<T> {
    const models = super.removeAll<T>(type);
    this.__cache.fetch[type] = {};
    this.__cache.fetchAll[type] = {};
    return models;
  }
 
  /**
   * 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
   */
  private __doFetch(query: IQueryParams, options?: IRequestOptions): Promise<Response> {
    return 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
   */
  private __handleErrors(response: Response) {
 
    /* istanbul ignore if */
    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
   */
  private __addRecord(obj: JsonApi.IRecord): Record {
    const {type, id} = obj;
    let record: Record = this.find(type, id) as Record;
    const flattened: IDictionary<any> = flattenRecord(obj);
 
    if (record) {
      record.update(flattened);
    } else if (this.static.types.filter((item) => item.type === obj.type).length) {
      record = this.add(flattened, obj.type) as Record;
    } else {
      record = new 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
    /* istanbul ignore else */
    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
   */
  private __updateRelationships(obj: JsonApi.IRecord): void {
    const record: IModel = this.find(obj.type, obj.id);
    const refs: Array<string> = obj.relationships ? Object.keys(obj.relationships) : [];
    refs.forEach((ref: string) => {
      const 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 && record) {
        const models: IModel|Array<IModel> = mapItems<IModel>(items, ({id, type}) => this.find(type, id) || id);
        const itemType: string = items instanceof Array ? items[0].type : items.type;
        record.assignRef(ref, models, itemType);
      }
    });
  }
 
  /**
   * 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
   */
  private __iterateEntries(body: JsonApi.IResponse, fn: Function) {
    mapItems((body && body.included) || [], fn);
    return mapItems<IModel>((body && body.data) || [], fn);
  }
}