All files / src/domain/ApiResponseHelper index.js

100% Statements 32/32
100% Branches 31/31
100% Functions 7/7
100% Lines 26/26
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      106x     40x   36x     30x     34x       17x   2x 14x 1x     13x 1x     12x 1x     11x 10x 10x 4x     6x 3x 2x     1x     3x 2x       2x     2x   2x                      
import { ApiResponse } from 'domain/ApiResponse';
import is from 'is_js';
 
const isApiResponse = (apiResponse) => is.object(apiResponse) &&
    apiResponse instanceof ApiResponse;
 
const isLoading = (apiResponse) => isApiResponse(apiResponse) && apiResponse.loading === true;
 
const hasFailed = (apiResponse) => isApiResponse(apiResponse) &&
    apiResponse.error instanceof Error;
 
const hasSucceeded = (apiResponse) => isApiResponse(apiResponse) &&
    is.not.undefined(apiResponse.data);
 
const fetchWasCalled = (apiResponse) => isLoading(apiResponse) ||
    hasFailed(apiResponse) ||
    hasSucceeded(apiResponse);
 
const shouldFetch = (apiResponse) => ! fetchWasCalled(apiResponse);
 
const create = (apiResponse) => {
  if (apiResponse instanceof ApiResponse) {
    return apiResponse;
  }
 
  if (apiResponse instanceof Error) {
    return new ApiResponse({ error: apiResponse });
  }
 
  if (is.undefined(apiResponse)) {
    return new ApiResponse();
  }
 
  if (is.object(apiResponse) && Object.keys(apiResponse).length === 1) {
    const key = Object.keys(apiResponse)[0];
    if (key === 'loading') {
      return new ApiResponse({ loading: apiResponse.loading === true });
    }
 
    if (key === 'error') {
      if (is.undefined(apiResponse.error) || apiResponse.error instanceof Error) {
        return new ApiResponse({ error: apiResponse.error });
      }
 
      return new ApiResponse({ error: new Error(apiResponse.error) });
    }
 
    if (key === 'data') {
      return new ApiResponse({ data: apiResponse.data });
    }
  }
 
  return new ApiResponse({ data: apiResponse });
};
 
const responsify = create;
 
export const ApiResponseHelper = {
  shouldFetch,
  fetchWasCalled,
  isLoading,
  hasFailed,
  hasSucceeded,
  create,
  responsify,
};
 
export default ApiResponseHelper;