【TypeScript】node-cacheを使ったChacheサービス実装

ヘッドレスCMSのContenftulでデータ管理をしてNext.jsでレンダリングしようとした時に、API Limitを考慮するためにChacheを導入した。

他サーバーと共通にするまでもなかったので、Redisではなくnode-cacheを導入した。

install package.

node-cacheをインストールします。

npm install node-cache --save

code

シングルトンのようにしたかったのでstaticでクラスインスタンスを持ち、

private static instance: NodeCache;

constructorでnewすることで持ち回るようにしています。

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

あとは、get、set、必要に応じてキャッシュ削除などのロジックを組み込みます。
setの第3引数はttlをsecondsで指定できるので、自動でキャッシュ削除したい時は設定します。

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

日本全国と海外を旅するノマドワーカー。5年間、技術営業として働いたのち独立。
フリーランスエンジニアとしてWebサイト制作やアプリケーション開発を行う。面白い人たちの面白いを世に届けるべく行動中。
2024年11月にポルトガルへ移住🇵🇹

目次