Chache service implementation using node-cache.

When we tried to manage the data in the headless CMS Contenftul and render it in Next.js, we introduced Chache to take API Limit into account.

We introduced node-cache instead of Redis because we didn’t need to share it with other servers.

I wanted it to be like a singleton, so I had a class instance with static,

private static instance: NodeCache;

It is brought around by new with constructor.

  constructor() {
    if (typeof CacheService.instance === "undefined") {
      CacheService.instance = new NodeCache();
    }
  }

The rest of the logic is built in, including get, set and, if necessary, cache deletion.
The third argument of set can be specified as ttl in seconds, so set it if you want to delete the cache automatically.

import NodeCache from "node-cache";

class CacheService {
  private static instance: NodeCache;

  constructor() {
    if (typeof CacheService.instance === "undefined") {
      CacheService.instance = new NodeCache();
    }
  }

  set(key: string, value: any) {
    CacheService.instance.set(key, value, 60);
  }

  get(key: string) {
    const value = CacheService.instance.get(key);
    if (value === "undefined") {
      return null;
    }
    return value;
  }

  del(keys: string[]) {
    CacheService.instance.del(keys);
  }

  getKeys() {
    return CacheService.instance.keys();
  }
}

export default new CacheService();
よかったらシェアしてね!
目次