npm package: @heavybit/hb-cache-package
Description: Shared cache package that allows microservices to set, get and delete cache data
Author: Nicholas Kute
Latest version: 1.0.12

# Cache Package

This is a shared caching library for microservices using Bull and Redis. It processes cache requests (get, set, delete) asynchronously using queues, providing scalability and resilience.

# Overview

The CacheService is a utility designed for managing cache operations using Redis. It allows other microservices to perform basic caching functionalities, including setting, retrieving, deleting, and invalidating cache data. This service is suitable for scenarios requiring fast access to frequently used data, reducing the load on the primary database and improving overall application performance.

# Features

Synchronous Cache Operations: Directly interact with Redis for immediate cache operations.
Role-Based Access: Ensures that only authorized services can access or modify cache data.
TTL Management: Supports setting cache expiration times.
Error Handling: Logs errors and handles connection issues gracefully.

# Installation

To use the CacheService in your microservice, follow these steps:

```
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);
```

### Parameters:

**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
}
```

### Parameters:

**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 });
```

### Parameters:

**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 });
```

### Parameters:

**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
);
```

### Parameters:

**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);
}
```

# Conclusion
The CacheService provides a simple and effective way for microservices to manage cache operations with Redis. By leveraging this service, you can improve data retrieval speeds and enhance the performance of your applications.