Skip to content

Commit

Permalink
feat(medusa, modules-sdk, types, utils): Re work modules loading and …
Browse files Browse the repository at this point in the history
…remove legacy functions (#5496)
  • Loading branch information
adrien2p authored Nov 2, 2023
1 parent ca411e5 commit 154c9b4
Show file tree
Hide file tree
Showing 39 changed files with 632 additions and 409 deletions.
8 changes: 8 additions & 0 deletions .changeset/rich-dragons-roll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@medusajs/medusa": patch
"@medusajs/modules-sdk": patch
"@medusajs/types": patch
"@medusajs/utils": patch
---

feat(medusa, modules-sdk, types, utils): Re work modules loading and remove legacy functions
13 changes: 8 additions & 5 deletions integration-tests/environment-helpers/bootstrap-app.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ async function bootstrapApp({ cwd, env = {} } = {}) {

const loaders = require("@medusajs/medusa/dist/loaders").default

const { container, dbConnection, pgConnection } = await loaders({
directory: path.resolve(cwd || process.cwd()),
expressApp: app,
isTest: false,
})
const { container, dbConnection, pgConnection, disposeResources } =
await loaders({
directory: path.resolve(cwd || process.cwd()),
expressApp: app,
isTest: false,
})

const PORT = await getPort()

return {
disposeResources,
container,
db: dbConnection,
pgConnection,
Expand Down Expand Up @@ -55,6 +57,7 @@ module.exports = {
expressServer.close(),
db?.destroy(),
pgConnection?.context?.destroy(),
container.dispose(),
])

if (typeof global !== "undefined" && global?.gc) {
Expand Down
1 change: 1 addition & 0 deletions integration-tests/plugins/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ module.exports = {
`/www/`,
`/dist/`,
`/node_modules/`,
"<rootDir>/node_modules",
`__tests__/fixtures`,
`__testfixtures__`,
`.cache`,
Expand Down
6 changes: 3 additions & 3 deletions packages/event-bus-local/src/services/event-bus-local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ eventEmitter.setMaxListeners(Infinity)

// eslint-disable-next-line max-len
export default class LocalEventBusService extends AbstractEventBusModuleService {
protected readonly logger_: Logger
protected readonly logger_?: Logger
protected readonly eventEmitter_: EventEmitter

constructor({ logger }: MedusaContainer & InjectedDependencies) {
Expand Down Expand Up @@ -53,7 +53,7 @@ export default class LocalEventBusService extends AbstractEventBusModuleService
event.eventName
)

this.logger_.info(
this.logger_?.info(
`Processing ${event.eventName} which has ${eventListenersCount} subscribers`
)

Expand All @@ -73,7 +73,7 @@ export default class LocalEventBusService extends AbstractEventBusModuleService
// @ts-ignore
await subscriber(...args)
} catch (e) {
this.logger_.error(
this.logger_?.error(
`An error occurred while processing ${event.toString()}: ${e}`
)
}
Expand Down
7 changes: 5 additions & 2 deletions packages/link-modules/src/migration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function getMigration(

const generator = orm.getSchemaGenerator()
if (hasTable) {
const updateSql = await generator.getUpdateSchemaSQL()
/* const updateSql = await generator.getUpdateSchemaSQL()
const entityUpdates = updateSql
.split(";")
.map((sql) => sql.trim())
Expand All @@ -65,7 +65,10 @@ export function getMigration(
}
} else {
logger.info(`Skipping "${tableName}" migration.`)
}
}*/
logger.info(
`Link module "${serviceName}" table update skipped because the table already exists. Please write your own migration if needed.`
)
} else {
try {
await generator.createSchema()
Expand Down
110 changes: 66 additions & 44 deletions packages/link-modules/src/utils/generate-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,72 @@ import { composeTableName } from "./compose-link-name"
export function generateGraphQLSchema(
joinerConfig: ModuleJoinerConfig,
primary: ModuleJoinerRelationship,
foreign: ModuleJoinerRelationship
foreign: ModuleJoinerRelationship,
{ logger }: { logger } = { logger: console }
) {
const fieldNames = primary.foreignKey.split(",").concat(foreign.foreignKey)

const entityName = toPascalCase(
"Link_" +
(joinerConfig.databaseConfig?.tableName ??
composeTableName(
primary.serviceName,
primary.foreignKey,
foreign.serviceName,
foreign.foreignKey
))
)
let fieldNames!: string[]
let entityName!: string

if (!joinerConfig.isReadOnlyLink) {
fieldNames = primary.foreignKey.split(",").concat(foreign.foreignKey)

entityName = toPascalCase(
"Link_" +
(joinerConfig.databaseConfig?.tableName ??
composeTableName(
primary.serviceName,
primary.foreignKey,
foreign.serviceName,
foreign.foreignKey
))
)
}

let typeDef = ""

for (const extend of joinerConfig.extends ?? []) {
const extendedModule = MedusaModule.getModuleInstance(extend.serviceName)
if (!extendedModule && !extend.relationship.isInternalService) {
throw new Error(
`Module ${extend.serviceName} not found. Please verify that the module is configured and installed, also the module must be loaded before the link modules.`
)
}

const extJoinerConfig = MedusaModule.getJoinerConfig(
extend.relationship.serviceName
)
let extendedEntityName =
extJoinerConfig?.linkableKeys?.[extend.relationship.foreignKey]!

if (!extendedEntityName && (!primary || !foreign)) {
logger.warn(
`Link modules schema: No linkable key found for ${extend.relationship.foreignKey} on module ${extend.relationship.serviceName}.`
)

continue
}

const fieldName = camelToSnakeCase(
lowerCaseFirst(extend.relationship.alias)
)

let type = extend.relationship.isList ? `[${entityName}]` : entityName
if (extJoinerConfig?.isReadOnlyLink) {
type = extend.relationship.isList
? `[${extendedEntityName}]`
: extendedEntityName
}

typeDef += `
extend type ${extend.serviceName} {
${fieldName}: ${type}
}
`
}

if (joinerConfig.isReadOnlyLink) {
return typeDef
}

// Pivot table fields
const fields = fieldNames.reduce((acc, curr) => {
Expand Down Expand Up @@ -48,7 +100,7 @@ export function generateGraphQLSchema(
composeTableName(foreign.serviceName)
)}`

let typeDef = `
typeDef += `
type ${entityName} {
${(Object.entries(fields) as any)
.map(
Expand All @@ -66,36 +118,6 @@ export function generateGraphQLSchema(
}
`

for (const extend of joinerConfig.extends ?? []) {
const extendedModule = MedusaModule.getModuleInstance(extend.serviceName)
if (!extendedModule && !extend.relationship.isInternalService) {
throw new Error(
`Module ${extend.serviceName} not found. Please verify that the module is configured and installed, also the module must be loaded before the link modules.`
)
}

const joinerConfig = MedusaModule.getJoinerConfig(extend.serviceName)
let extendedEntityName =
joinerConfig?.linkableKeys?.[extend.relationship.primaryKey]!

if (!extendedEntityName) {
continue
}

extendedEntityName = toPascalCase(extendedEntityName)

const linkTableFieldName = camelToSnakeCase(
lowerCaseFirst(extend.relationship.alias)
)
const type = extend.relationship.isList ? `[${entityName}]` : entityName

typeDef += `
extend type ${extendedEntityName} {
${linkTableFieldName}: ${type}
}
`
}

return typeDef
}

Expand Down
10 changes: 6 additions & 4 deletions packages/medusa-core-utils/src/parse-cors-origins.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { buildRegexpIfValid } from "./build-regexp-if-valid";
import { buildRegexpIfValid } from "./build-regexp-if-valid"

export function parseCorsOrigins(str: string): (string | RegExp)[] {
return str.split(",").map((subStr) => {
return buildRegexpIfValid(subStr) ?? subStr
})
return !str
? []
: str.split(",").map((subStr) => {
return buildRegexpIfValid(subStr) ?? subStr
})
}
14 changes: 11 additions & 3 deletions packages/medusa/src/api/routes/admin/store/get-store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { ModulesHelper } from "@medusajs/modules-sdk"
import { FlagRouter } from "@medusajs/utils"
import { defaultRelationsExtended } from "."
import {
Expand All @@ -7,6 +6,7 @@ import {
StoreService,
} from "../../../../services"
import { ExtendedStoreDTO } from "../../../../types/store"
import { MedusaModule } from "@medusajs/modules-sdk"

/**
* @oas [get] /admin/store
Expand Down Expand Up @@ -62,7 +62,6 @@ export default async (req, res) => {
const storeService: StoreService = req.scope.resolve("storeService")

const featureFlagRouter: FlagRouter = req.scope.resolve("featureFlagRouter")
const modulesHelper: ModulesHelper = req.scope.resolve("modulesHelper")

const paymentProviderService: PaymentProviderService = req.scope.resolve(
"paymentProviderService"
Expand All @@ -80,7 +79,16 @@ export default async (req, res) => {
})) as ExtendedStoreDTO

data.feature_flags = featureFlagRouter.listFlags()
data.modules = modulesHelper.modules
data.modules = MedusaModule.getLoadedModules()
.map((loadedModule) => {
return Object.entries(loadedModule).map(([key, service]) => {
return {
module: key,
resolution: service.__definition.defaultPackage,
}
})
})
.flat()

const paymentProviders = await paymentProviderService.list()
const fulfillmentProviders = await fulfillmentProviderService.list()
Expand Down
27 changes: 14 additions & 13 deletions packages/medusa/src/commands/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,24 @@ import {
} from "../services"
import getMigrations, { getModuleSharedResources } from "./utils/get-migrations"

import { ConfigModule } from "../types/global"
import { CreateProductCategoryInput } from "../types/product-category"
import { CreateProductInput } from "../types/product"
import { IPricingModuleService } from "@medusajs/types"
import IsolatePricingDomainFeatureFlag from "../loaders/feature-flags/isolate-pricing-domain"
import Logger from "../loaders/logger"
import PublishableApiKeyService from "../services/publishable-api-key"
import { SalesChannel } from "../models"
import { sync as existsSync } from "fs-exists-cached"
import express from "express"
import featureFlagLoader from "../loaders/feature-flags"
import fs from "fs"
import { sync as existsSync } from "fs-exists-cached"
import { getConfigFile } from "medusa-core-utils"
import { handleConfigError } from "../loaders/config"
import loaders from "../loaders"
import path from "path"
import { track } from "medusa-telemetry"
import path from "path"
import loaders from "../loaders"
import { handleConfigError } from "../loaders/config"
import featureFlagLoader from "../loaders/feature-flags"
import IsolatePricingDomainFeatureFlag from "../loaders/feature-flags/isolate-pricing-domain"
import Logger from "../loaders/logger"
import { SalesChannel } from "../models"
import PublishableApiKeyService from "../services/publishable-api-key"
import { ConfigModule } from "../types/global"
import { CreateProductInput } from "../types/product"
import { CreateProductCategoryInput } from "../types/product-category"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"

type SeedOptions = {
directory: string
Expand Down Expand Up @@ -122,7 +123,7 @@ const seed = async function ({ directory, migrate, seedFile }: SeedOptions) {
"shippingProfileService"
)
const pricingModuleService: IPricingModuleService = container.resolve(
"pricingModuleService"
ModuleRegistrationName.PRICING
)
/* eslint-enable */

Expand Down
23 changes: 19 additions & 4 deletions packages/medusa/src/commands/utils/get-migrations.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MedusaModule, registerModules } from "@medusajs/modules-sdk"
import { MedusaModule, registerMedusaModule } from "@medusajs/modules-sdk"
import fs from "fs"
import { sync as existsSync } from "fs-exists-cached"
import glob from "glob"
Expand Down Expand Up @@ -96,8 +96,13 @@ function resolvePlugin(pluginName) {

export function getInternalModules(configModule) {
const modules = []
const moduleResolutions = {}

const moduleResolutions = registerModules(configModule.modules)
Object.entries(configModule.modules ?? {}).forEach(([moduleKey, module]) => {
moduleResolutions[moduleKey] = registerMedusaModule(moduleKey, module)[
moduleKey
]
})

for (const moduleResolution of Object.values(moduleResolutions)) {
if (
Expand Down Expand Up @@ -256,7 +261,12 @@ export const getModuleSharedResources = (configModule, featureFlagsRouter) => {
}

export const runIsolatedModulesMigration = async (configModule) => {
const moduleResolutions = registerModules(configModule.modules)
const moduleResolutions = {}
Object.entries(configModule.modules ?? {}).forEach(([moduleKey, module]) => {
moduleResolutions[moduleKey] = registerMedusaModule(moduleKey, module)[
moduleKey
]
})

for (const moduleResolution of Object.values(moduleResolutions)) {
if (
Expand All @@ -276,7 +286,12 @@ export const runIsolatedModulesMigration = async (configModule) => {
}

export const revertIsolatedModulesMigration = async (configModule) => {
const moduleResolutions = registerModules(configModule.modules)
const moduleResolutions = {}
Object.entries(configModule.modules ?? {}).forEach(([moduleKey, module]) => {
moduleResolutions[moduleKey] = registerMedusaModule(moduleKey, module)[
moduleKey
]
})

for (const moduleResolution of Object.values(moduleResolutions)) {
if (
Expand Down
Loading

0 comments on commit 154c9b4

Please sign in to comment.