Raw
1 import { LoaderOptions } from "@medusajs/framework/types"
2 import { asValue } from "@medusajs/framework/awilix"
3 import Redis from "ioredis"
4 import { RedisCacheModuleOptions } from "../types"
5
6 export default async ({
7 container,
8 logger,
9 options,
10 }: LoaderOptions): Promise<void> => {
11 const { redisUrl, redisOptions } = options as RedisCacheModuleOptions
12
13 if (!redisUrl) {
14 throw Error(
15 "No `redisUrl` provided in `cacheService` module options. It is required for the Redis Cache Module."
16 )
17 }
18
19 const connection = new Redis(redisUrl, {
20 // Lazy connect to properly handle connection errors
21 lazyConnect: true,
22 ...(redisOptions ?? {}),
23 })
24
25 try {
26 await connection.connect()
27 logger?.info(`Connection to Redis in module 'cache-redis' established`)
28 } catch (err) {
29 logger?.error(
30 `An error occurred while connecting to Redis in module 'cache-redis': ${err}`
31 )
32 }
33
34 container.register({
35 cacheRedisConnection: asValue(connection),
36 })
37 }