Skip to content

Commit

Permalink
create loaders onApplicationStart
Browse files Browse the repository at this point in the history
  • Loading branch information
pKorsholm committed Jan 17, 2024
1 parent ae8a5a1 commit c9c22a4
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ describe("AuthenticationModuleService - AuthProvider", () => {
schema: process.env.MEDUSA_PRICING_DB_SCHEMA,
},
})

if(service.__hooks?.onApplicationStart) {
await service.__hooks.onApplicationStart()
}
})

afterEach(async () => {
Expand Down
45 changes: 12 additions & 33 deletions packages/authentication/src/loaders/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ import * as defaultProviders from "@providers"

import { LoaderOptions, ModulesSdkTypes } from "@medusajs/types"

import { AuthProviderService } from "@services"
import { ServiceTypes } from "@types"
import { asClass } from "awilix"
import { AwilixContainer, ClassOrFunctionReturning, Resolver, asClass, asFunction, asValue } from "awilix"

export default async ({
container,
options,
}: LoaderOptions<
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
Expand All @@ -19,40 +16,22 @@ export default async ({

const providersToLoad = Object.values(defaultProviders)

const authProviderService: AuthProviderService = container.resolve(
"authProviderService"
)
let providers

try {
providers = await authProviderService.list({
provider: providersToLoad.map((p) => p.PROVIDER),
})
} catch (error) {
if (error.name === "TableNotFoundException") {
// we are running loaders in migrations (or fail at a later point)
return
}
}

const loadedProviders = new Map(providers.map((p) => [p.provider, p]))

const providersToCreate: ServiceTypes.CreateAuthProviderDTO[] = []

for (const provider of providersToLoad) {
container.register({
[`auth_provider_${provider.PROVIDER}`]: asClass(provider).singleton(),
})
}

if (loadedProviders.has(provider.PROVIDER)) {
continue
}
container.register({
[`auth_providers`]: asArray(providersToLoad),
})
}

providersToCreate.push({
provider: provider.PROVIDER,
name: provider.DISPLAY_NAME,
})
function asArray(
resolvers: (ClassOrFunctionReturning<unknown> | Resolver<unknown>)[]
): { resolve: (container: AwilixContainer) => unknown[] } {
return {
resolve: (container: AwilixContainer) =>
resolvers.map((resolver) => container.build(resolver)),
}

await authProviderService.create(providersToCreate)
}
45 changes: 35 additions & 10 deletions packages/authentication/src/services/authentication-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { AuthProvider, AuthUser } from "@models"

import { joinerConfig } from "../joiner-config"
import { AuthProviderService, AuthUserService } from "@services"

import {
InjectManager,
InjectTransactionManager,
Expand All @@ -29,6 +30,7 @@ import {
FilterableAuthUserProps,
UpdateAuthUserDTO,
} from "@medusajs/types/dist/authentication/common"
import { ServiceTypes } from "@types"

type InjectedDependencies = {
baseRepository: DAL.RepositoryService
Expand All @@ -45,6 +47,33 @@ export default class AuthenticationModuleService<
return joinerConfig
}

__hooks = {
onApplicationStart: async () => {
const providersToLoad = this.__container__["auth_providers"]

const providers = await this.authProviderService_.list({
provider: providersToLoad.map((p) => p.provider),
})

const loadedProvidersMap = new Map(providers.map((p) => [p.provider, p]))

const providersToCreate: ServiceTypes.CreateAuthProviderDTO[] = []

for (const provider of providersToLoad) {
if (loadedProvidersMap.has(provider.provider)) {
continue
}

providersToCreate.push({
provider: provider.provider,
name: provider.displayName,
})
}

await this.authProviderService_.create(providersToCreate)
},
}

protected __container__: MedusaContainer
protected baseRepository_: DAL.RepositoryService

Expand Down Expand Up @@ -351,10 +380,8 @@ export default class AuthenticationModuleService<
): AbstractAuthenticationModuleProvider {
let containerProvider: AbstractAuthenticationModuleProvider
try {
console.log("containerProvider")
containerProvider = this.__container__[`auth_provider_${provider}`]
} catch (error) {
console.log(error)
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`AuthenticationProvider with for provider: ${provider} wasn't registered in the module. Have you configured your options correctly?`
Expand All @@ -369,18 +396,16 @@ export default class AuthenticationModuleService<
provider: string,
authenticationData: Record<string, unknown>,
@MedusaContext() sharedContext: Context = {}
): Promise<AuthenticationResponse> {
let registeredProvider
console.log("hello")
try {
): Promise<AuthenticationResponse> {
let registeredProvider

try {
await this.retrieveAuthProvider(provider, {})

console.log(registeredProvider)
registeredProvider = this.getRegisteredAuthenticationProvider(provider)

return await registeredProvider.authenticate(authenticationData)
} catch (error) {
console.log(JSON.stringify(error, null, 2))
} catch (error) {
return { success: false, error: error.message }
}
}
Expand Down
16 changes: 16 additions & 0 deletions packages/types/src/authentication/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,22 @@ export abstract class AbstractAuthenticationModuleProvider {
public static PROVIDER: string
public static DISPLAY_NAME: string

public get provider() {
return (this.constructor as Function & { PROVIDER: string}).PROVIDER
}

public get displayName() {
return (this.constructor as Function & { DISPLAY_NAME: string}).DISPLAY_NAME
}

public getProvider(): string {
return (this.constructor as Function & { PROVIDER: string}).PROVIDER
}

public getDisplayName(): string {
return (this.constructor as Function & { DISPLAY_NAME: string, PROVIDER: string}).PROVIDER
}

abstract authenticate(
data: Record<string, unknown>
): Promise<AuthenticationResponse>
Expand Down

0 comments on commit c9c22a4

Please sign in to comment.