Source:data-loader.service.js

(function () {
  'use strict';
  // Data Loader
  angular
    .module('mohistory')
    .service('dataLoader', dataLoader);
  dataLoader.$inject = ['$q', '$http', '$injector', '$cacheFactory', '$location', 'configSeparated', 'currentEnvironment'];
  /**
   * A service for requesting information from various APIs.
   * @memberof mohistory
   * @name dataLoader
   * @ngdoc service
   */
  function dataLoader($q, $http, $injector, $cacheFactory, $location, configSeparated, currentEnvironment) {
    var service = this;
    /* ----- Variables ----- */
    var wpAPI = configSeparated[currentEnvironment].WP_PATH;
    service.CONTEXT_ENDPOINTS = {
      'exhibits': 'exhibits/',
      'events': 'events/',
      'posts': 'blog/',
      'pages': 'pages/',
      'presskits': 'presskits/',
      'mediaroom': 'mediaroom/',
    };
    // Used to clean path for redirect.php
    service.PATH_COMPLETION = {
      'exhibits': 'exhibits/',
      'events': 'events/',
      'posts': 'posts/',
      'pages': '',
      'presskits': 'presskits/',
      'mediaroom': 'mediaroom/',
      '': '',
    };
    service.REQ_HEADER = {
      'Content-Type': 'text/plain',
    };
    /* ----- Function Bindings ----- */
    service.getPartsContext = getPartsContext;
    service.getMenus = getMenus;
    service.getCollectionLists = getCollectionLists;
    service.getCalendar = getCalendar;
    /* ----- Function Definitions ----- */
    /**
     * Retrieve the page data from the WordPress API.
     * @function getPartsContext
     * @memberof dataLoader
     * @param {string} dataID Id, or slug, representing an item to retrieve given a particular context
     * @param {string} context Type of data to retrieve, e.g. posts, pages, or events
     * @return {object} Promise representing the request to the API
     */
    function getPartsContext(dataID, context) {
      // Web does not understand presskits
      if (context === 'presskits' && wpAPI.indexOf('web') >= 0) {
        context = 'mediaroom';
      }
      // If there is a context endpoint add it to the request URL
      var fullURL = service.CONTEXT_ENDPOINTS[context] ? wpAPI + service.CONTEXT_ENDPOINTS[context] + dataID : wpAPI + dataID;
      $http.defaults.headers.common['Content-Type'] = 'text/plain';
      $http.defaults.headers.common['Accept'] = 'text/plain';
      return $http({
        method: 'GET',
        url: fullURL,
        headers: service.REQ_HEADER
      }).then(function (response) {
        if (response['data']['og:title'] === undefined || response['data']['og:title'] === null || response['data']['mhs:parts'] === undefined || response['data']['mhs:parts'] === null) {
          // Something is wrong with the API and it returned a 200 range status code. 
          // Redirect to maintenance page.
          throw new Error('api_error');
        } else {
          return response.data;
        }
      }).catch(function (error) {
        if (error.message === 'api_error') {
          // Something is wrong with the API
          handleMajorError();
        } else if (context !== 'pages') {
          // Before giving up and passing control to resolve.php, check if it is a two 
          // slug WordPress page. We can do this by redirecting to the main.firstIDsecondID 
          // route and letting it handle its own resolve.
          $injector.get('$state').go('main.firstIDsecondID', {
            firstID: context,
            secondID: dataID
          });
        } else {
          // Received a 404, so redirect to the redirection script
          handleError(error, service.PATH_COMPLETION[context] + dataID, error.status);
          throw new Error('Redirecting');
        }
      });
    }
    /**
     * Retrieve the header and footer menu links. Cache the the information while the app
     * is active in the browser.
     * @function getMenus
     * @memberof dataLoader
     */
    function getMenus() {
      var deferred = $q.defer();
      // Retrieve cached information
      var dataCache = $cacheFactory.get('mohistoryCache');
      // If nothing has been cached already, creat the cache.
      if (!dataCache) {
        dataCache = $cacheFactory('mohistoryCache');
      }
      // Pull the data out of the cache object
      var menuData = dataCache.get('menu');
      // If there was data in the cache object, resolve promise
      if (menuData) {
        deferred.resolve(menuData);
      } else {
        // Last resort, load data from local file
        $http.get('data/menu.json').then(function (response) {
          // Cache the data and resolve the promise
          dataCache.put('menu', response.data);
          deferred.resolve(response.data);
        }).catch(function (error) {
          // If we cannot load menu, redirect to maintenance page.
          handleMajorError();
          deferred.reject(error);
        });
      }
      return deferred.promise;
    }
    /**
     * Retrieve the data for the collection and finding aid lists.
     * @function getCollectionLists
     * @memberof dataLoader
     * @param {string} fileName Name of the JSON file to open.
     * @return {object} A promise representing the file request
     */
    function getCollectionLists(fileName) {
      var deferred = $q.defer();
      // Retrieve cached information
      var dataCache = $cacheFactory.get('mohistoryCache');
      // If nothing has been cached already, creat the cache.
      if (!dataCache) {
        dataCache = $cacheFactory('mohistoryCache');
      }
      // Pull the data out of the cache object
      var colList = dataCache.get(fileName);
      // If there was data in the cache object, resolve promise
      if (colList) {
        deferred.resolve(colList);
      } else {
        // Last resort, load data from local file
        $http.get(fileName).then(function (response) {
          // Cache the data and resolve the promise
          dataCache.put(fileName, response.data);
          deferred.resolve(response.data);
        }).catch(function (error) {
          // If we cannot load the data, redirect to maintenance page.
          handleMajorError();
          deferred.reject(error);
        });
      }
      return deferred.promise;
    }
    /**
     * Retrieve data for the calendar on the event search page.
     * @function getCalendar
     * @memberof dataLoader
     * @return {object} A promise representing the file request
     */
    function getCalendar() {
      var deferred = $q.defer();
      // Retrieve cached information
      var dataCache = $cacheFactory.get('mohistoryCache');
      // If nothing has been cached already, creat the cache.
      if (!dataCache) {
        dataCache = $cacheFactory('mohistoryCache');
      }
      // Pull the data out of the cache object
      var calendarData = dataCache.get('calendar');
      // If there was data in the cache object, resolve promise
      if (calendarData) {
        deferred.resolve(calendarData);
      } else {
        // Last resort, load data from local file
        $http.get('data/calendar.json').then(function (response) {
          // Cache the data and resolve the promise
          dataCache.put('calendar', response.data);
          deferred.resolve(response.data);
        }).catch(function (error) {
          // If we cannot load the data, redirect to maintenance page.
          handleMajorError();
          deferred.reject(error);
        });
      }
      return deferred.promise;
    }
    /**
     * Redirect to the maintenance page, this only occurs if the site is broken.
     * @memberof dataLoader
     * @function handleMajorError
     */
    function handleMajorError() {
      console.log('API Error Redirecting - http://mohistory.org/maintenance.html');
      window.location.href = 'http://mohistory.org/maintenance.html';
    }
    /**
     * Redirect to the resolver, so it can determine the best next steps.
     * @memberof dataLoader
     * @function handleError
     * @param {object} error The problem as reported by the API
     * @param {string} path URL which produced the error
     * @param {string} status Status returned by the API
     */
    function handleError(error, path, status) {
      console.log('Error Redirecting - http://utils.mohistory.org/resolve' + '?path=' + $location.absUrl() + '&status=' + status)
      window.location.href = 'http://utils.mohistory.org/resolve' + '?path=' + $location.absUrl() + '&status=' + status;
    }
  }
})();