Travis D
Travis D

Reputation: 317

Can't get node-cache to persist data between requests

I'm writing an API endpoint in node and can't seem to get node-cache to work. I've played around with the TTL, key names and anything else I can think of. What am I missing?

const NodeCache = require( "node-cache" );

export const getLiveFeed = async (
) => {
  const cache = new NodeCache({ stdTTL: 10000000, checkperiod: 120 });
  const cacheKey = 'liveFeed';
  let items = cache.get(cacheKey);
  console.log(`Got ${items} from the cache...`);
  console.log(cache.getStats());
  if (Array.isArray(items)) {
    console.log(`Got ${items.length} from the cache`);
    return items;
  }
  items = [1, 2, 3, 4, 5];
  cache.set(cacheKey, items);
  console.log(cache.getStats());
  console.log(`Setting ${items.length} items in the cache`);
  return items;
};
~

Making multiple requests to the endpoint produces:

Got undefined from the cache...
{ hits: 0, misses: 1, keys: 0, ksize: 0, vsize: 0 }
{ hits: 0, misses: 1, keys: 1, ksize: 8, vsize: 200 }
Setting 5 items in the cache
Got undefined from the cache...
{ hits: 0, misses: 1, keys: 0, ksize: 0, vsize: 0 }
{ hits: 0, misses: 1, keys: 1, ksize: 8, vsize: 200 }
Setting 5 items in the cache
Got undefined from the cache...
{ hits: 0, misses: 1, keys: 0, ksize: 0, vsize: 0 }
{ hits: 0, misses: 1, keys: 1, ksize: 8, vsize: 200 }
Setting 5 items in the cache

Upvotes: 0

Views: 1283

Answers (1)

Travis D
Travis D

Reputation: 317

I see now, I have to declare the cache outside of the function.

const NodeCache = require( "node-cache" );
const cache = new NodeCache({ stdTTL: 10000000, checkperiod: 120 });

export const getLiveFeed = async (
) => {
....
}

Upvotes: 2

Related Questions