|
1
|
{"slug":"/references/caching-module-provider","title":"How to Create a Caching Module Provider","frontmatter":{"slug":"/references/caching-module-provider","tags":["caching","server","how to"],"sidebar_label":"Create Caching Provider","keywords":["caching","provider","integration"]},"toc":[{"title":"Implementation Example","id":"implementation-example","level":2},{"title":"1. Create Module Provider Directory","id":"1-create-module-provider-directory","level":2},{"title":"2. Create the Caching Module Provider Service","id":"2-create-the-caching-module-provider-service","level":2},{"title":"constructor","id":"constructor","level":3},{"title":"Example","id":"example","level":4},{"title":"Identifier","id":"identifier","level":3},{"title":"clear","id":"clear","level":3},{"title":"Example","id":"example-1","level":4},{"title":"Parameters","id":"clear-parameters","level":4},{"title":"Returns","id":"clear-returns","level":4},{"title":"get","id":"get","level":3},{"title":"Example","id":"example-2","level":4},{"title":"Parameters","id":"get-parameters","level":4},{"title":"Returns","id":"get-returns","level":4},{"title":"set","id":"set","level":3},{"title":"Example","id":"example-3","level":4},{"title":"Parameters","id":"set-parameters","level":4},{"title":"Returns","id":"set-returns","level":4},{"title":"3. Create Module Definition File","id":"3-create-module-definition-file","level":2},{"title":"4. Use Module Provider","id":"4-use-module-provider","level":2},{"title":"5. Test it Out","id":"5-test-it-out","level":2},{"title":"Useful Guides","id":"useful-guides","level":2}],"blocks":[{"kind":"markdown","html":"In this guide, you’ll learn how to create a Caching Module Provider and the methods you must implement in its main service."},{"kind":"note","variant":"note","html":"The Caching Module and its providers are available starting [Medusa v2.11.0](https://github.com/medusajs/medusa/releases/tag/v2.11.0)."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"Implementation Example","id":"implementation-example"},{"kind":"markdown","html":"As you implement your Caching Module Provider, it can be useful to refer to an existing provider and how it's implemeted.\n\nIf you need to refer to an existing implementation as an example, check the [Redis Caching Module Provider in the Medusa repository](https://github.com/medusajs/medusa/tree/develop/packages/modules/providers/caching-redis).\n\n---"},{"kind":"heading","level":2,"text":"1. Create Module Provider Directory","id":"1-create-module-provider-directory"},{"kind":"markdown","html":"Start by creating a new directory for your module provider.\n\nIf you're creating the module provider in a Medusa application, create it under the `src/modules` directory. For example, `src/modules/my-caching`.\n\nIf you're creating the module provider in a plugin, create it under the `src/providers` directory. For example, `src/providers/my-caching`."},{"kind":"note","variant":"note","html":"The rest of this guide always uses the `src/modules/my-caching` directory as an example."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"2. Create the Caching Module Provider Service","id":"2-create-the-caching-module-provider-service"},{"kind":"markdown","html":"Create the file `src/modules/my-caching/service.ts` that holds the module provider's main service. It must implement the `ICachingProviderService` interface imported from `@medusajs/framework/types`:\n\n```ts title=\"src/modules/my-caching/service.ts\"\nimport { ICachingProviderService } from \"@medusajs/framework/types\"\n\nclass MyCachingProviderService implements ICachingProviderService {\n // TODO implement methods\n}\n\nexport default MyCachingProviderService\n```"},{"kind":"heading","level":3,"text":"constructor","id":"constructor"},{"kind":"markdown","html":"The constructor allows you to access resources from the module's container using the first parameter,\nand the module's options using the second parameter.\n\nIf you're creating a client or establishing a connection with a third-party service, do it in a [Loader](https://docs.medusajs.com/learn/fundamentals/modules/loaders)\nand store it in the Module's container. Then, you can access it in your service using the container."},{"kind":"note","variant":"note","title":"Loader Example","html":"[Initialize MongoDB client in loader and access it in service](https://docs.medusajs.com/learn/fundamentals/modules/loaders#example-register-custom-mongodb-connection)."},{"kind":"heading","level":4,"text":"Example","id":"example"},{"kind":"markdown","html":"```ts\nimport { ICachingProviderService } from \"@medusajs/framework/types\"\nimport { Logger } from \"@medusajs/framework/types\"\n\ntype InjectedDependencies = {\n logger: Logger\n // assuming you initialized a client\n // in a Loader and stored it in the container\n client: Client\n}\n\ntype Options = {\n url: string\n}\n\nclass MyCachingModuleProvider implements ICachingProviderService {\n static identifier = \"my-cache\"\n protected logger_: Logger\n protected options_: Options\n protected client\n\n constructor (\n { logger, client }: InjectedDependencies,\n options: Options\n ) {\n this.logger_ = logger\n this.options_ = options\n // set the service's client to\n // the client from the container\n this.client = client\n }\n\n // ...\n}\n\nexport default MyCachingModuleProvider\n```"},{"kind":"heading","level":3,"text":"Identifier","id":"identifier"},{"kind":"markdown","html":"Every caching module provider must have an `identifier` static property. The provider's ID\nwill be stored as `lp_{identifier}_{id}`, where `id` is the ID you set in your `medusa-config.ts` file.\n\nFor example:\n\n```ts\nclass MyCachingModuleProvider implements ICachingProviderService {\n static identifier = \"my-cache\"\n // ...\n}\n```"},{"kind":"heading","level":3,"text":"clear","id":"clear"},{"kind":"markdown","html":"This method clears data from the cache. If no options are specified, all items matching the key or tags should be cleared.\nOtherwise, if `options.autoInvalidate` is `true`, only items that were set with `options.autoInvalidate: true` should be cleared.\n\nItems with `options.autoInvalidate: false` should only be cleared when no options are provided.\n\nIf neither `key` nor `tags` are provided, nothing should be cleared."},{"kind":"heading","level":4,"text":"Example","id":"example-1"},{"kind":"markdown","html":"```ts\nasync clear({ key, tags, options, }: { \n key?: string; \n tags?: string[]; \n options?: { autoInvalidate?: boolean }\n}): Promise<void> {\n if (!options) {\n // clear all items\n await this.client.invalidate({ key, tags })\n } else if (options.autoInvalidate) {\n // clear only items with autoInvalidate option set to true\n const keysToDelete: string[] = []\n const storedOptions = await this.client.get({ key, tags, pipeline: \"options\" })\n storedOptions.forEach((item) => {\n if (item.autoInvalidate) {\n keysToDelete.push(item.key as string)\n }\n })\n await this.client.invalidate({ keys: keysToDelete })\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"clear-parameters"},{"kind":"typeList","sectionTitle":"clear","types":[{"name":"param0","type":"`object`","description":"The parameters 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. All items with any of the provided tags should be cleared.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"options","type":"`object`","description":"Options for clearing the item(s). The options should be 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 should be 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":[]}]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"clear-returns"},{"kind":"typeList","sectionTitle":"clear","types":[{"name":"Promise","type":"Promise<void>","optional":false,"defaultValue":"","description":"A promise that resolves when the item(s) have been cleared.","expandable":false,"children":[]}]},{"kind":"heading","level":3,"text":"get","id":"get"},{"kind":"markdown","html":"This method retrieves data from the cache either by `key` or `tags`. If neither `key` nor `tags` are provided, `null` should be returned.\nIf both `key` and `tags` are provided, `key` should take precedence over `tags`."},{"kind":"heading","level":4,"text":"Example","id":"example-2"},{"kind":"markdown","html":"```ts\nclass MyCachingModuleProvider implements ICachingProviderService {\n // ...\n async get({ key, tags }: { key?: string; tags?: string[] }): Promise<any> {\n // Assuming you're using a client to get data\n if (key) {\n return await this.client.get({ key })\n }\n if (tags) {\n return await this.client.getByTags({ tags })\n }\n return null\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"get-parameters"},{"kind":"typeList","sectionTitle":"get","types":[{"name":"param0","type":"`object`","description":"The parameters for retrieving the item.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"key","type":"`string`","description":"The key of the item to retrieve. If both are provided, `key` should take precedence over `tags`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"tags","type":"`string`[]","description":"The tags of the items to retrieve. All items with any of the provided tags should be retrieved.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"get-returns"},{"kind":"typeList","sectionTitle":"get","types":[{"name":"Promise","type":"Promise<any>","optional":false,"defaultValue":"","description":"The item(s) that was stored in the cache, or `null` if not found.","expandable":false,"children":[{"name":"any","type":"`any`","optional":false,"defaultValue":"","description":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":3,"text":"set","id":"set"},{"kind":"markdown","html":"This method stores data in the cache. It should also store the options with the item, \nallowing you to later to check the `autoInvalidate` option when clearing the item."},{"kind":"heading","level":4,"text":"Example","id":"example-3"},{"kind":"markdown","html":"```ts\nclass MyCachingModuleProvider implements ICachingProviderService {\n // ...\n async set({ key, data, ttl, tags, options }: { \n key: string; \n data: any; \n ttl?: number; \n tags?: string[]; \n options?: { autoInvalidate?: boolean } \n }): Promise<void> {\n // Assuming you're using a client to set data\n await this.client.set({ key, data, ttl, tags })\n await this.client.set({ key, data: options, pipeline: \"options\" })\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"set-parameters"},{"kind":"typeList","sectionTitle":"set","types":[{"name":"param0","type":"`object`","description":"The parameters 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. Items should be grouped together using tags for retrieval or invalidation.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"options","type":"`object`","description":"Options for storing the item. The options should be 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":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"set-returns"},{"kind":"typeList","sectionTitle":"set","types":[{"name":"Promise","type":"Promise<void>","optional":false,"defaultValue":"","description":"A promise that resolves when the item has been stored.","expandable":false,"children":[]}]},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"3. Create Module Definition File","id":"3-create-module-definition-file"},{"kind":"markdown","html":"Create the file `src/modules/my-caching/index.ts` with the following content:\n\n```ts title=\"src/modules/my-caching/index.ts\"\nimport { ModuleProvider, Modules } from \"@medusajs/framework/utils\"\nimport MyCachingProviderService from \"./service\"\n\nexport default ModuleProvider(Modules.CACHING, {\n services: [MyCachingProviderService],\n})\n```\n\nThis exports the module provider's definition, indicating that the `MyCachingProviderService` is the module provider's service.\n\n---"},{"kind":"heading","level":2,"text":"4. Use Module Provider","id":"4-use-module-provider"},{"kind":"markdown","html":"To use your Caching Module Provider, add it to the `providers` array of the Caching Module in `medusa-config.ts`:\n\n```ts title=\"medusa-config.ts\"\nmodule.exports = defineConfig({\n // ...\n modules: [\n {\n resolve: \"@medusajs/medusa/caching\",\n options: {\n providers: [\n {\n // if module provider is in a plugin, use `plugin-name/providers/my-caching`\n resolve: \"./src/modules/my-caching\",\n id: \"my-caching\",\n // set this if you want this provider to be used by default\n // and you have other Caching Module Providers registered.\n is_default: true,\n options: {\n url: \"http://example.com\",\n // provider options...\n }\n },\n ]\n }\n }\n ]\n})\n```\n\n\n---"},{"kind":"heading","level":2,"text":"5. Test it Out","id":"5-test-it-out"},{"kind":"markdown","html":"To test out your Caching Module Provider, create a simple API route that retrieves cached data with Query:\n\n```ts title=\"src/api/test-caching/route.ts\"\nimport { MedusaRequest, MedusaResponse } from \"@medusajs/framework/http\"\n\nexport const GET = async (req: MedusaRequest, res: MedusaResponse) => {\n const query = req.scope.resolve(\"query\")\n\n const { data } = await query.graph({\n entity: \"product\",\n fields: [\"id\", \"title\"],\n }, {\n cache: {\n enable: true,\n providers: [\"my-caching\"], // use your provider id here\n }\n })\n\n res.status(200).json({ data })\n}\n```\n\nThen, start your Medusa server with the following command:\n\n```bash npm2yarn\nnpm run dev\n```\n\nNext, send a `GET` request to `http://localhost:9000/test-caching`:\n\n```bash\ncurl http://localhost:9000/test-caching\n```\n\nYou will receive a response with the list of products. The first time you make this request, the products will be fetched from the database and cached in memory. Subsequent requests will retrieve the products from the cache, which improves performance.\n\n\n---"},{"kind":"heading","level":2,"text":"Useful Guides","id":"useful-guides"},{"kind":"markdown","html":"- [How to Use Caching Module](/references/caching-service)"}]} |