Back to Medusa

How to Use Caching Module

www/apps/resources/references/caching/interfaces/caching.ICachingModuleService/page.mdx

2.14.214.9 KB
Original Source

import { TypeList } from "docs-ui"

How to Use Caching Module

In this guide, you’ll learn about the different methods in the Caching Module's service and how to use them.

:::note

The Caching Module and its providers are available starting Medusa v2.11.0.

:::

:::tip

You should use the Caching Module's service when you're caching computed data or data from external APIs. To cache database query results, enable caching in Query or Index Module instead.

:::


Resolve Caching Module's Service

In your workflow's step, you can resolve the Caching Module's service from the Medusa container:

ts
import { Modules } from "@medusajs/framework/utils"
import { createStep } from "@medusajs/framework/workflows-sdk"

const step1 = createStep(
  "step-1",
  async ({}, { container }) => {
    const cachingModuleService = container.resolve(
      Modules.CACHING
    )
    
    // TODO use cachingModuleService
  } 
)

You can then use the Caching Module's service's methods in the step. The rest of this guide details these methods.


clear

This method clears data from the cache. If neither key nor tags are provided, nothing is cleared.

By default, all items matching the key or tags are cleared regardless of their options. If you provide options.autoInvalidate: true, only items that were set with options.autoInvalidate: true are cleared.

For example, if you set options.autoInvalidate: true, only items that were set with options.autoInvalidate: true are cleared. Items that were set with options.autoInvalidate: false are only cleared when you don't provide any options.

Example

To invalidate cache by key:

ts
await cachingModuleService.clear({
 key: "products" // this key would typically be a hash
})

This example will clear the item with the key products regardless of its options.autoInvalidate value.

To invalidate cache by tags:

ts
await cachingModuleService.clear({
 tags: ["Product:list:*"]
})

This example will clear all items with the tag Product:list:* regardless of their options.autoInvalidate value.

To invalidate only the cache data that were set to automatically invalidate:

ts
await cachingModuleService.clear({
 tags: ["Product:list:*"],
 options: { autoInvalidate: true }
})

This example will only clear items with the tag Product:list:* that were set with options.autoInvalidate: true. Items that were set with options.autoInvalidate: false will not be cleared.

:::note

Setting options.autoInvalidate: false when calling the clear method will not clear any items. To clear items that were set with options.autoInvalidate: false, you must call the clear method without any options.

:::

To invalidate cache from specific providers:

ts
await cachingModuleService.clear({
 key: "products",
 providers: ["caching-redis", "caching-memcached"]
})

This example will try to clear the data from both the caching-redis and caching-memcached providers.

Parameters

<TypeList types={[{"name":"param0","type":"object","description":"The options for clearing the item(s).","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"key","type":"string","description":"The key of the item to clear.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"tags","type":"string[]","description":"The tags of the items to clear. Tags\nare useful to clear multiple related items at once.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"options","type":"object","description":"Options for clearing the item(s). The options are matched against the stored options when the item was set.\nFor example, if the item was set with autoInvalidate: true, it will only be cleared if the autoInvalidate option is also set to true.\nIf not provided, all items matching the key or tags are cleared regardless of their options.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"autoInvalidate","type":"boolean","description":"Whether to clear item(s) that were set to automatically invalidate.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"providers","type":"string[]","description":"The providers from which to clear the item(s). You can specify an array of provider IDs.\nIf not provided, the default provider is used.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="clear"/>

Returns

<TypeList types={[{"name":"Promise","type":"Promise<void>","optional":false,"defaultValue":"","description":"A promise that resolves when the item(s) have been cleared.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="clear"/>


computeKey

This method computes a cache key based on the input object. It's useful to generate consistent and unique keys for caching.

Example

ts
const key = await cachingModuleService.computeKey({
  id: "prod_123",
  title: "Product 123"
})
// key will be a hash string like "a1b2c3d4e5f6g7h8i9j0"

Parameters

<TypeList types={[{"name":"input","type":"object","description":"The input object to compute the key from.","optional":false,"defaultValue":"","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="computeKey"/>

Returns

<TypeList types={[{"name":"Promise","type":"Promise<string>","optional":false,"defaultValue":"","description":"The computed cache key.","expandable":false,"children":[{"name":"string","type":"string","optional":false,"defaultValue":"","description":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="computeKey"/>


computeTags

This method computes cache tags based on the input object. It's useful to generate consistent and relevant tags for caching.

Example

ts
const tags = await cachingModuleService.computeTags({
  products: [{ id: "prod_123" }, { id: "prod_456" }],
}, {
  operation: "updated"
})
// tags might be ["Product:prod_123", "Product:prod_456", "Product:list:*"]

Parameters

<TypeList types={[{"name":"input","type":"object","description":"The input object to compute the tags from.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"options","type":"Record<string, any>","description":"Additional options to influence tag computation.","optional":true,"defaultValue":"","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="computeTags"/>

Returns

<TypeList types={[{"name":"Promise","type":"Promise<string[]>","optional":false,"defaultValue":"","description":"An array of computed cache tags.","expandable":false,"children":[{"name":"string[]","type":"string[]","optional":false,"defaultValue":"","description":"","expandable":false,"children":[{"name":"string","type":"string","optional":false,"defaultValue":"","description":"","expandable":false,"children":[]}]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="computeTags"/>


get

This method retrieves data from the cache. If neither key nor tags are provided, or the item is not found, null is returned.

Example

To retrieve by key:

ts
const data = await cachingModuleService.get({
  key: "products", // this key would typically be a hash
}) as { id: string; title: string; }

To retrieve by tags:

ts
const data = await cachingModuleService.get({
  tags: ["Product:list:*"],
}) as { id: string; title: string; }[]

To retrieve by key from specific providers:

ts
const data = await cachingModuleService.get({
  key: "products", // this key would typically be a hash
  providers: ["caching-redis", "caching-memcached"]
}) as { id: string; title: string; }

This example will try to get the data from the caching-redis provider first, and if not found, it will try to get it from the caching-memcached provider.

Parameters

<TypeList types={[{"name":"param0","type":"object","description":"The options for retrieving the item.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"key","type":"string","description":"The key of the item to retrieve.\nIf both key and tags are provided, key takes precedence over tags.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"tags","type":"string[]","description":"The tags of the items to retrieve. Tags\nare useful to retrieve multiple related items at once.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"providers","type":"string[]","description":"The providers to retrieve the item(s) from. You can specify an array of provider IDs.\nThey're checked in the order they're provided in, so make sure to order them based on your priority.\nIf not provided, the default provider is used.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="get"/>

Returns

<TypeList types={[{"name":"Promise","type":"Promise<any>","optional":false,"defaultValue":"","description":"The item(s) that was stored in the cache. If no item was found, or neither key nor tags were provided, null is returned.","expandable":false,"children":[{"name":"any","type":"any","optional":false,"defaultValue":"","description":"","expandable":false,"children":[]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="get"/>


set

This method stores data in the cache using the default Caching Module Provider.

Example

To store with key:

ts
const data = { id: "prod_123", title: "Product 123" }
const key = await cachingModuleService.computeKey(data)
await cachingModuleService.set({
  key,
  data
})

To store with tags:

:::note

Tags should follow conventions to ensure they're automatically invalidated.

:::

ts
const data = [{ id: "prod_123", title: "Product 123" }]
const key = await cachingModuleService.computeKey(data)
await cachingModuleService.set({
  key,
  data,
  tags: [`Product:${data[0].id}`, "Product:list:*"]
})

To disable auto-invalidation for the item:

ts
const data = [{ id: "prod_123", title: "Product 123" }]
const key = await cachingModuleService.computeKey(data)
await cachingModuleService.set({
  key,
  data,
  options: { autoInvalidate: false }
})

The item is now only invalidated when calling the clear method directly with the same key or tags.

To store with specific providers:

ts
const data = { id: "prod_123", title: "Product 123" }
const key = await cachingModuleService.computeKey(data)
await cachingModuleService.set({
  key,
  data,
  providers: [
    "caching-redis",
    { id: "caching-memcached", ttl: 120 } // custom TTL for this provider
  ]
})

This example will store the item in both the caching-redis and caching-memcached providers, with a custom TTL of 120 seconds for the caching-memcached provider.

Parameters

<TypeList types={[{"name":"param0","type":"object","description":"The options for storing the item.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"key","type":"string","description":"The key of the item to store.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"data","type":"object","description":"The data to store in the cache.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"ttl","type":"number","description":"The time-to-live (TTL in seconds) value in seconds.\nIf not provided, the default TTL value configured in the provider should be used.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"tags","type":"string[]","description":"The tags of the items to store. Tags are useful to group related items \ntogether for retrieval or invalidation.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"options","type":"object","description":"Options for storing the item. The options are stored with the item, allowing you to later match against them when clearing the item.\nFor example, if you set autoInvalidate: false, the item will only be invalidated when calling the clear method directly with the same key or tags.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"autoInvalidate","type":"boolean","description":"Whether to automatically invalidate the item when related data changes.","optional":true,"defaultValue":"true","expandable":false,"children":[]}]},{"name":"providers","type":"Providers","description":"The providers to store the item(s) in. You can specify an array of provider IDs or an array of objects with provider ID and TTL.\nIf not provided, the default provider is used.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"string","description":"The ID of the provider to use, as set in medusa-config.ts.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"ttl","type":"number","description":"Optional custom time-to-live (TTL) (in seconds) for this provider. If not provided, the default TTL configured\nin the provider is used, or the default TTL of the Caching Module if not configured in the provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="set"/>

Returns

<TypeList types={[{"name":"Promise","type":"Promise<void>","optional":false,"defaultValue":"","description":"A promise that resolves when the item has been stored.","expandable":false,"children":[]}]} expandUrl="https://docs.medusajs.com/learn/fundamentals/data-models/manage-relationships#retrieve-records-of-relation" sectionTitle="set"/>