All files / src/lib request.js

100% Statements 16/16
100% Branches 13/13
100% Functions 4/4
100% Lines 16/16
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      8x                         13x 13x     13x 1x       12x 1x         178x 178x 87x   178x           5x 5x   5x       5x         24x          
import SheetrockError from './error';
 
// Provide a simple state store shared across requests.
const stateCache = {
  defaults: {
    failed: false,
    header: 0,
    labels: null,
    loaded: false,
    offset: 0,
  },
  store: {},
};
 
class Request {
  constructor(options) {
    this.options = options;
    this.index = options.requestIndex;
 
    // Abandon requests that have previously generated an error.
    if (this.state.failed) {
      throw new SheetrockError('A previous request for this resource failed.');
    }
 
    // Abandon requests that have already been loaded.
    if (this.state.loaded) {
      throw new SheetrockError('No more rows to load!');
    }
  }
 
  get state() {
    const reset = this.options.user.reset || this.options.request.data;
    if (!{}.hasOwnProperty.call(stateCache.store, this.index) || reset) {
      stateCache.store[this.index] = Object.assign({}, stateCache.defaults);
    }
    return stateCache.store[this.index];
  }
 
  // Assemble a full URI for the query.
  get url() {
    // If requested, make a request for paged data.
    const size = this.options.user.fetchSize;
    const pageQuery = (size) ? ` limit ${size + 1} offset ${this.state.offset}` : '';
 
    const queryVars = [
      `gid=${encodeURIComponent(this.options.request.gid)}`,
      `tq=${encodeURIComponent(this.options.user.query + pageQuery)}`,
    ];
    return this.options.request.apiEndpoint + queryVars.join('&');
  }
 
  // Extend exsiting attributes with passed attributes.
  update(attributes = {}) {
    stateCache.store[this.index] = Object.assign(this.state, attributes);
  }
}
 
export default Request;