How to Create a Cache Module

In this guide, you’ll learn how to create a Cache Module.

1. Create Module Directory#

Start by creating a new directory for your module. For example, src/modules/my-cache.


2. Create the Cache Service#

Create the file src/modules/my-cache/service.ts that holds the implementation of the cache service.

The Cache Module's main service must implement the ICacheService interface imported from @medusajs/framework/types:

src/modules/my-cache/service.ts
1import { ICacheService } from "@medusajs/framework/types"2
3class MyCacheService implements ICacheService {4  get<T>(key: string): Promise<T> {5    throw new Error("Method not implemented.")6  }7  set(key: string, data: unknown, ttl?: number): Promise<void> {8    throw new Error("Method not implemented.")9  }10  invalidate(key: string): Promise<void> {11    throw new Error("Method not implemented.")12  }13}14
15export default MyCacheService

The service implements the required methods based on the desired caching mechanism.

Implement get Method#

The get method retrieves the value of a cached item based on its key.

The method accepts a string as a first parameter, which is the key in the cache. It either returns the cached item or null if it doesn’t exist.

For example, to implement this method using Memcached:

src/modules/my-cache/service.ts
1class MyCacheService implements ICacheService {2  // ...3  async get<T>(cacheKey: string): Promise<T | null> {4    return new Promise((res, rej) => {5      this.memcached.get(cacheKey, (err, data) => {6        if (err) {7          res(null)8        } else {9          if (data) {10            res(JSON.parse(data))11          } else {12            res(null)13          }14        }15      })16    })17  }18}

Implement set Method#

The set method is used to set an item in the cache. It accepts three parameters:

  1. The first parameter is a string indicating the key of the data being added to the cache. This key can be used later to get or invalidate the cached item.
  2. The second parameter is the data to be added to the cache. The data can be of any type.
  3. The third parameter is optional. It’s a number indicating how long (in seconds) the data should be kept in the cache.

For example, to implement this method using Memcached:

src/modules/my-cache/service.ts
1class MyCacheService implements ICacheService {2  protected TTL = 603  // ...4  async set(5    key: string,6    data: Record<string, unknown>,7    ttl: number = this.TTL // or any value8  ): Promise<void> {9    return new Promise((res, rej) =>10      this.memcached.set(11        key, JSON.stringify(data), ttl, (err) => {12        if (err) {13          rej(err)14        } else {15          res()16        }17      })18    )19  }20}

Implement invalidate Method#

The invalidate method removes an item from the cache using its key.

By default, items are removed from the cache when their time-to-live (ttl) expires. The invalidate method can be used to remove the item beforehand.

The method accepts a string as a first parameter, which is the key of the item to invalidate and remove from the cache.

For example, to implement this method using Memcached:

src/modules/my-cache/service.ts
1class MyCacheService implements ICacheService {2  // ...3  async invalidate(key: string): Promise<void> {4    return new Promise((res, rej) => {5      this.memcached.del(key, (err) => {6        if (err) {7          rej(err)8        } else {9          res()10        }11      })12    })13  }14}

3. Create Module Definition File#

Create the file src/modules/my-cache/index.ts with the following content:

src/modules/my-cache/index.ts
1import MyCacheService from "./service"2import { Module } from "@medusajs/framework/utils"3
4export default Module("my-cache", {5  service: MyCacheService,6})

This exports the module's definition, indicating that the MyCacheService is the main service of the module.


4. Use Module#

To use your Cache Module, add it to the modules object exported as part of the configurations in medusa-config.ts. A Cache Module is added under the cacheService key.

For example:

medusa-config.ts
1import { Modules } from "@medusajs/framework/utils"2
3// ...4
5module.exports = defineConfig({6  // ...7  modules: [8    {9      resolve: "./src/modules/my-cache",10      options: {11        // any options12        ttl: 30,13      },14    },15  ],16})
Was this page helpful?
Edit this page