1 import { asValue } from "@medusajs/framework/awilix"
2 import { LoaderOptions } from "@medusajs/framework/types"
3 import Redis from "ioredis"
4 import { EOL } from "os"
5 import { EventBusRedisModuleOptions } from "../types"
6
7 export default async ({
8 container,
9 logger,
10 options,
11 }: LoaderOptions): Promise<void> => {
12 const {
13 redisUrl,
14 redisOptions,
15 queueName,
16 queueOptions,
17 workerOptions,
18 jobOptions,
19 } = options as EventBusRedisModuleOptions
20
21 if (!redisUrl) {
22 throw Error(
23 "No `redisUrl` provided in project config. It is required for the Redis Event Bus."
24 )
25 }
26
27 const connection = new Redis(redisUrl, {
28 // Required config. See: https://github.com/OptimalBits/bull/blob/develop/CHANGELOG.md#breaking-changes
29 maxRetriesPerRequest: null,
30 enableReadyCheck: false,
31 // Lazy connect to properly handle connection errors
32 lazyConnect: true,
33 ...(redisOptions ?? {}),
34 })
35
36 try {
37 await new Promise(async (resolve) => {
38 await connection.connect(resolve)
39 })
40 logger?.info(`Connection to Redis in module 'event-bus-redis' established`)
41 } catch (err) {
42 logger?.error(
43 `An error occurred while connecting to Redis in module 'event-bus-redis':${EOL} ${err}`
44 )
45 }
46
47 container.register({
48 eventBusRedisConnection: asValue(connection),
49 eventBusRedisQueueName: asValue(queueName ?? "events-queue"),
50 eventBusRedisQueueOptions: asValue(queueOptions ?? {}),
51 eventBusRedisWorkerOptions: asValue(workerOptions ?? {}),
52 eventBusRedisJobOptions: asValue(jobOptions ?? {}),
53 })
54 }