1 import {
2 Constructor,
3 ILockingProvider,
4 Logger,
5 } from "@medusajs/framework/types"
6 import { MedusaError } from "@medusajs/framework/utils"
7 import { LockingProviderRegistrationPrefix } from "../types"
8
9 type InjectedDependencies = {
10 [key: `lp_${string}`]: ILockingProvider
11 logger?: Logger
12 }
13
14 export default class LockingProviderService {
15 protected __container__: InjectedDependencies
16 #logger: Logger
17
18 constructor(container: InjectedDependencies) {
19 this.__container__ = container
20 this.#logger = container["logger"]
21 ? container.logger
22 : (console as unknown as Logger)
23 }
24
25 static getRegistrationIdentifier(
26 providerClass: Constructor<ILockingProvider>
27 ) {
28 if (!(providerClass as any).identifier) {
29 throw new MedusaError(
30 MedusaError.Types.INVALID_ARGUMENT,
31 `Trying to register a locking provider without an identifier.`
32 )
33 }
34 return `${(providerClass as any).identifier}`
35 }
36
37 public retrieveProviderRegistration(providerId: string): ILockingProvider {
38 try {
39 return this.__container__[
40 `${LockingProviderRegistrationPrefix}${providerId}`
41 ]
42 } catch (err) {
43 if (err.name === "AwilixResolutionError") {
44 const errMessage = `
45 Unable to retrieve the locking provider with id: ${providerId}
46 Please make sure that the provider is registered in the container and it is configured correctly in your project configuration file.`
47
48 // Log full error for debugging
49 this.#logger.error(`AwilixResolutionError: ${err.message}`, err)
50
51 throw new Error(errMessage)
52 }
53
54 const errMessage = `Unable to retrieve the locking provider with id: ${providerId}, the following error occurred: ${err.message}`
55 this.#logger.error(errMessage)
56
57 throw new Error(errMessage)
58 }
59 }
60 }