1 import { MedusaContainer } from "@medusajs/types"
2 import {
3 asFunction,
4 asValue,
5 AwilixContainer,
6 ClassOrFunctionReturning,
7 createContainer,
8 Resolver,
9 } from "@medusajs/deps/awilix"
10
11 function asArray(
12 resolvers: (ClassOrFunctionReturning<unknown> | Resolver<unknown>)[]
13 ): { resolve: (container: AwilixContainer) => unknown[] } {
14 return {
15 resolve: (container: AwilixContainer) =>
16 resolvers.map((resolver) => container.build(resolver)),
17 }
18 }
19
20 function registerAdd(
21 this: MedusaContainer,
22 name: string,
23 registration: typeof asFunction | typeof asValue
24 ) {
25 const storeKey = name + "_STORE"
26
27 if (this.registrations[storeKey] === undefined) {
28 this.register(storeKey, asValue([] as Resolver<unknown>[]))
29 }
30 const store = this.resolve(storeKey) as (
31 | ClassOrFunctionReturning<unknown>
32 | Resolver<unknown>
33 )[]
34
35 if (this.registrations[name] === undefined) {
36 this.register(name, asArray(store))
37 }
38 store.unshift(registration)
39
40 return this
41 }
42
43 export function createMedusaContainer(...args): MedusaContainer {
44 const container = createContainer.apply(null, args) as MedusaContainer
45
46 container.registerAdd = registerAdd.bind(container)
47
48 const originalScope = container.createScope
49 container.createScope = () => {
50 const scoped = originalScope() as MedusaContainer
51 scoped.registerAdd = registerAdd.bind(scoped)
52
53 return scoped
54 }
55
56 return container
57 }