Shared cache package that allows microservices to set, get and delete cache data
npm install @heavybit/hb-cache-package
npm install @pesalink/cache-package
`
Environment Variables
The following environment variables can be set to configure the Redis connection:
REDIS_HOST: Hostname of the Redis server (default: 127.0.0.1).
REDIS_PORT: Port number of the Redis server (default: 6379).
REDIS_USER: Username for Redis authentication (if applicable).
REDIS_PASSWORD: Password for Redis authentication (if applicable).
Import the CacheService:
Include the CacheService in your microservice:
`
const CacheService = require('@pesalink/cache-package');
`
Initialize the CacheService:
Create an instance of the CacheService:
`
const cacheService = new CacheService();
`
Usage
Setting Cache Data
To store data in the cache:
`
await cacheService.setCache({ entity: 'user', id: userId }, userData);
`
$3
keyObj: An object representing the cache key (e.g., { entity: 'user', id: userId }).
value: The data to cache (e.g., user information).
expiryInSeconds (optional): The time in seconds before the cache expires (default: 3600 seconds).
Getting Cache Data
To retrieve data from the cache:
`
const data = await cacheService.getCache({ entity: 'user', id: userId });
if (!data) {
// Fetch from DB and set in cache if not found
}
`
$3
keyObj: An object representing the cache key (e.g., { entity: 'user', id: userId }).
Deleting Cache Data
To delete specific cache data:
`
await cacheService.deleteCache({ entity: 'user', id: userId });
`
$3
keyObj: An object representing the cache key (e.g., { entity: 'user', id: userId }).
Invalidating Cache
To invalidate a cache entry:
`
await cacheService.invalidateCache({ entity: 'user', id: userId });
`
$3
keyObj: An object representing the cache key (e.g., { entity: 'user', id: userId }).
Fetching Data with Cache Support
To fetch data with cache support (returning cached data if available, otherwise fetching from the database):
`
const data = await cacheService.getCachedData(
{ entity: 'user', id: userId },
async () => await fetchUserFromDB(userId) // Your method to fetch from DB
);
`
$3
cacheKey: An object representing the cache key.
dbFetchMethod: A function that fetches data from the database if the cache is empty.
Closing the Connection
To gracefully close the Redis connection when the service is no longer needed:
`
await cacheService.disconnect();
`
Error Handling
The CacheService logs errors for failed Redis operations. It is recommended to handle potential exceptions in your code:
`
try {
await cacheService.setCache({ entity: 'user', id: userId }, userData);
} catch (error) {
console.error('Failed to set cache:', error);
}
``