How to cache a http api request for a determined time?


#1

Hi,

I am trying to cache a http request to a forecast api, for 5 minutes and I don’t know how to do it.
What i have until now it’s caching first request and then it’s giving result from cache forever.

I can’t find any documentation or samples on how to achieve this.
I also tried to use https://github.com/jmdobry/angular-cache but I can’t make it work with ionic.

Thanks!

This is may code:

app.factory('ForecastCache', function ($cacheFactory) {
  return $cacheFactory('ForecastCache', {
    capacity: 3,
  });
});

app.factory('Forecast', function($log, $AuthService, $http, Settings, $config, $cacheFactory, ForecastCache) {

  $log.info('Forecast factory loaded');

  var forecastConditions = null;

  var url = 'https://api.forecast.io/forecast/' + $config.FORECASTIO_KEY +'/';

  var getWeatherAtLocation = function(lat, lng) {

    if(ForecastCache.get('forecastConditions')) {
      forecastConditions = ForecastCache.get('forecastConditions');
      $log.info('From cache');
      $log.info(forecastConditions);
    } else {
      forecastConditions = $http.jsonp(url + lat + ',' + lng + '?callback=JSON_CALLBACK' +
      '&units=' + Settings.units + '&lang=' + Settings.lang,{ cache: true});
      ForecastCache.put('forecastConditions', forecastConditions);

      $log.info('Cached');
      $log.info(forecastConditions);

    }

    return forecastConditions;

  } // End getWeatherAtLocation

  return {

    getWeatherAtLocation: function (lat, lng) {
      return getWeatherAtLocation(lat, lng);
    }

  }