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();
シェア!

この記事を書いた人

kenichiのアバター kenichi エンジニア・写真家 | Engineer and photographer

Nomadic worker who travels all over Japan and abroad; worked as a technical sales person for five years before going independent.
Works as a freelance engineer on website production and application development. Currently working to bring interesting things by interesting people to the world, while seeking to move abroad.

目次