All files / src/containers/ApiCalls ApiState.js

80.95% Statements 17/21
71.43% Branches 10/14
90% Functions 9/10
80.95% Lines 17/21
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    5x 5x 5x                       78x                 10x       48x                 20x       81x       14x       14x       12x       12x       25x       25x       14x 6x     8x                  
import { Record } from 'immutable';
 
const STATE_LOADING = 'loading';
const STATE_SUCCEEDED = 'succeeded';
const STATE_FAILED = 'failed';
 
export class NotAnInstanceOfApiCallValue extends Error { }
 
class ApiStateRecord extends Record({
  status: undefined,
  error: undefined,
  timestamp: undefined,
  id: undefined,
  disableDefault: undefined,
}) {
  constructor(values = {}) {
    super(Object.assign({},
        values,
        { disableDefault: !! values.disableDefault },
        { timestamp: new Date() }));
  }
}
 
export default class ApiState {
  static createSucceeded(id) {
    return new ApiStateRecord({ id, status: STATE_SUCCEEDED });
  }
 
  static createFailed(id, error, { disableDefault } = {}) {
    return new ApiStateRecord({
      id,
      status: STATE_FAILED,
      error,
      disableDefault,
    });
  }
 
  static createLoading(id, { disableDefault } = {}) {
    return new ApiStateRecord({ id, status: STATE_LOADING, disableDefault });
  }
 
  static isValue(value) {
    return value instanceof ApiStateRecord;
  }
 
  static isLoading(value) {
    Iif (! ApiState.isValue(value)) {
      throw new NotAnInstanceOfApiCallValue();
    }
 
    return value.status === STATE_LOADING;
  }
 
  static hasSucceeded(value) {
    Iif (! ApiState.isValue(value)) {
      throw new NotAnInstanceOfApiCallValue();
    }
 
    return value.status === STATE_SUCCEEDED;
  }
 
  static hasFailed(value) {
    Iif (! ApiState.isValue(value)) {
      throw new NotAnInstanceOfApiCallValue();
    }
 
    return value.status === STATE_FAILED;
  }
 
  static shouldPerform(state) {
    if (! ApiState.isValue(state)) {
      return true;
    }
 
    return ! ApiState.isLoading(state) &&
        ! ApiState.hasSucceeded(state) &&
        ! ApiState.hasFailed(state);
  }
 
  static getTimestamp(state) {
    state.get('timestamp');
  }
}