nodejs cache data

const NodeCache = require('node-cache');
const myCache = new NodeCache();

// Step 1: Set data in the cache
myCache.set('key', 'value', 10); // key, value, and time-to-live in seconds

// Step 2: Retrieve data from the cache
const cachedValue = myCache.get('key');

// Step 3: Check if data exists in the cache
if (cachedValue !== undefined) {
  // Data is available in the cache
  console.log('Data from cache:', cachedValue);
} else {
  // Data is not in the cache or has expired
  console.log('Data not found in cache. Fetching from the source...');

  // Step 4: Fetch data from the source (e.g., a database or external API)
  const fetchedData = fetchDataFromSource();

  // Step 5: Set the fetched data in the cache for future use
  myCache.set('key', fetchedData, 10);
  console.log('Data fetched from the source and set in cache:', fetchedData);
}

// Function to simulate fetching data from a source (e.g., a database or external API)
function fetchDataFromSource() {
  // Simulating a delay in fetching data
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Fetched data from source');
    }, 2000);
  });
}