1 import {
2 Context,
3 DAL,
4 InferEntityType,
5 Logger,
6 NotificationTypes,
7 } from "@medusajs/framework/types"
8 import { ModulesSdkUtils } from "@medusajs/framework/utils"
9 import { NotificationProvider } from "@models"
10 import { NotificationProviderRegistrationPrefix } from "@types"
11
12 type InjectedDependencies = {
13 logger?: Logger
14 notificationProviderRepository: DAL.RepositoryService<
15 InferEntityType<typeof NotificationProvider>
16 >
17 [
18 key: `${typeof NotificationProviderRegistrationPrefix}${string}`
19 ]: NotificationTypes.INotificationProvider
20 }
21
22 type Provider = InferEntityType<typeof NotificationProvider>
23
24 export default class NotificationProviderService extends ModulesSdkUtils.MedusaInternalService<
25 InjectedDependencies,
26 typeof NotificationProvider
27 >(NotificationProvider) {
28 protected readonly notificationProviderRepository_: DAL.RepositoryService<
29 InferEntityType<typeof NotificationProvider>
30 >
31
32 // We can store the providers in a memory since they can only be registered on startup and not changed during runtime
33
34 #logger: Logger
35
36 protected providersCache: Map<
37 string,
38 InferEntityType<typeof NotificationProvider>
39 >
40
41 constructor(container: InjectedDependencies) {
42 super(container)
43 this.notificationProviderRepository_ =
44 container.notificationProviderRepository
45 this.#logger = container["logger"]
46 ? container.logger
47 : (console as unknown as Logger)
48 }
49
50 protected retrieveProviderRegistration(
51 providerId: string
52 ): NotificationTypes.INotificationProvider {
53 try {
54 return this.__container__[
55 `${NotificationProviderRegistrationPrefix}${providerId}`
56 ]
57 } catch (err) {
58 if (err.name === "AwilixResolutionError") {
59 const errMessage = `
60 Unable to retrieve the notification provider with id: ${providerId}
61 Please make sure that the provider is registered in the container and it is configured correctly in your project configuration file.`
62
63 // Log full error for debugging
64 this.#logger.error(`AwilixResolutionError: ${err.message}`, err)
65
66 throw new Error(errMessage)
67 }
68
69 const errMessage = `Unable to retrieve the notification provider with id: ${providerId}, the following error occurred: ${err.message}`
70 this.#logger.error(errMessage)
71
72 throw new Error(errMessage)
73 }
74 }
75
76 async getProviderForChannels<
77 TChannel = string | string[],
78 TOutput = TChannel extends string[] ? Provider[] : Provider | undefined
79 >(channels: TChannel, sharedContext: Context = {}): Promise<TOutput> {
80 if (!this.providersCache) {
81 const providers = await this.notificationProviderRepository_.find(
82 {
83 where: { is_enabled: true },
84 },
85 sharedContext
86 )
87
88 this.providersCache = new Map(
89 providers.flatMap((provider) =>
90 provider.channels.map((c) => [c, provider])
91 )
92 )
93 }
94
95 const normalizedChannels = Array.isArray(channels) ? channels : [channels]
96 const results = normalizedChannels
97 .map((channel) => this.providersCache.get(channel))
98 .filter(Boolean)
99
100 return (Array.isArray(channels) ? results : results[0]) as TOutput
101 }
102
103 async send(
104 provider: InferEntityType<typeof NotificationProvider>,
105 notification: NotificationTypes.ProviderSendNotificationDTO
106 ): Promise<NotificationTypes.ProviderSendNotificationResultsDTO> {
107 const providerHandler = this.retrieveProviderRegistration(provider.id)
108 return await providerHandler.send(notification)
109 }
110 }