How to cache API responses using $cacheFactory

Loading

In AngularJS, you can use $cacheFactory to cache API responses and reduce the number of requests made to the server. Caching is a technique to store the response data temporarily, which can improve the performance of your application by reducing the latency and load on the server.

1. Understanding $cacheFactory

$cacheFactory is a service in AngularJS that allows you to create and manage in-memory caches. It provides a simple key-value store where you can cache responses. This cache can be used with the $http service to store responses for specific requests.

2. Creating and Configuring a Cache

You can create a cache instance using $cacheFactory. Once the cache is created, you can store the API responses in the cache, and later retrieve them when needed.

Example: Creating a Cache

angular.module('myApp', [])
.controller('MainController', function($scope, $http, $cacheFactory) {
// Create a cache using $cacheFactory
var myCache = $cacheFactory('myCache');

// Example GET request with cache
$scope.getData = function() {
// First, check if the data is available in the cache
var cachedData = myCache.get('dataKey');

if (cachedData) {
// If data is in the cache, use it
$scope.data = cachedData;
console.log('Data from cache:', cachedData);
} else {
// If data is not in the cache, make an HTTP request
$http.get('/api/data')
.then(function(response) {
// Store the response data in the cache
myCache.put('dataKey', response.data);
// Set the data to the scope
$scope.data = response.data;
console.log('Data from API:', response.data);
})
.catch(function(error) {
console.error('Error fetching data:', error);
});
}
};
});

Explanation:

  • Creating the Cache:
    • var myCache = $cacheFactory('myCache'); creates a cache named myCache.
  • Checking the Cache:
    • myCache.get('dataKey') checks if the data for the key dataKey is already stored in the cache.
  • Storing Data in Cache:
    • myCache.put('dataKey', response.data); stores the response data in the cache with the key dataKey.
  • Using Cached Data:
    • If data is found in the cache, it is used directly without making a new HTTP request.

3. Using Cache with $http

You can use $cacheFactory in conjunction with $http for automatic caching of API responses. AngularJS provides a built-in mechanism to cache HTTP requests using the $httpProvider configuration.

Example: Caching API Responses Automatically

angular.module('myApp', [])
.config(function($httpProvider) {
// Enable caching globally
$httpProvider.defaults.cache = $cacheFactory('myCache');
})
.controller('MainController', function($scope, $http) {
// Make a GET request
$http.get('/api/data')
.then(function(response) {
// Set the data to the scope
$scope.data = response.data;
})
.catch(function(error) {
console.error('Error fetching data:', error);
});
});

Explanation:

  • Global Cache:
    • $httpProvider.defaults.cache = $cacheFactory('myCache'); configures the $http service to use the cache created by $cacheFactory('myCache') for all HTTP requests.
  • Automatic Caching:
    • By default, the response of any HTTP GET request will be cached. If a request with the same URL is made again, the cached data will be returned instead of making a new request.

4. Manually Invalidating Cache

You can manually invalidate the cache by using the remove() or removeAll() methods of the cache object.

Example: Invalidating Cache

angular.module('myApp', [])
.controller('MainController', function($scope, $http, $cacheFactory) {
var myCache = $cacheFactory('myCache');

// Function to clear cache manually
$scope.clearCache = function() {
// Remove a specific item from the cache
myCache.remove('dataKey');

// Alternatively, clear all cache data
// myCache.removeAll();
console.log('Cache cleared');
};

$scope.getData = function() {
var cachedData = myCache.get('dataKey');

if (cachedData) {
$scope.data = cachedData;
console.log('Data from cache:', cachedData);
} else {
$http.get('/api/data')
.then(function(response) {
myCache.put('dataKey', response.data);
$scope.data = response.data;
console.log('Data from API:', response.data);
})
.catch(function(error) {
console.error('Error fetching data:', error);
});
}
};
});

Explanation:

  • Removing Specific Cache Item:
    • myCache.remove('dataKey'); removes the cached item with the key dataKey.
  • Removing All Cache:
    • myCache.removeAll(); clears all items from the cache.

5. Cache Expiration

The $cacheFactory does not provide built-in expiration mechanisms. However, you can implement a cache expiration strategy manually by setting time limits.

Example: Cache Expiration Based on Time

angular.module('myApp', [])
.controller('MainController', function($scope, $http, $cacheFactory, $timeout) {
var myCache = $cacheFactory('myCache');
var cacheExpirationTime = 5 * 60 * 1000; // 5 minutes

$scope.getData = function() {
var cachedData = myCache.get('dataKey');

if (cachedData) {
var cacheTime = cachedData.timestamp;
var currentTime = Date.now();

// Check if cache has expired
if (currentTime - cacheTime < cacheExpirationTime) {
$scope.data = cachedData.data;
console.log('Data from cache:', cachedData.data);
return;
} else {
myCache.remove('dataKey'); // Remove expired cache
}
}

$http.get('/api/data')
.then(function(response) {
var cacheData = {
data: response.data,
timestamp: Date.now() // Store the timestamp of when the cache was created
};

myCache.put('dataKey', cacheData);
$scope.data = response.data;
console.log('Data from API:', response.data);
})
.catch(function(error) {
console.error('Error fetching data:', error);
});
};
});

Explanation:

  • Cache Expiration Logic:
    • The data is stored in the cache along with a timestamp (timestamp: Date.now()).
    • Before using cached data, we check if the time difference between the current time and the cache timestamp is within the expiration limit.
    • If the cache has expired, it is removed using myCache.remove('dataKey').

Leave a Reply

Your email address will not be published. Required fields are marked *