feat(link-modules,modules-sdk, utils, types, products) - Remote Link and Link modules (#4695)
What:
- Definition of all Modules links
- `link-modules` package to manage the creation of all pre-defined link or custom ones
```typescript
import { initialize as iniInventory } from "@medusajs/inventory";
import { initialize as iniProduct } from "@medusajs/product";
import {
initialize as iniLinks,
runMigrations as migrateLinks
} from "@medusajs/link-modules";
await Promise.all([iniInventory(), iniProduct()]);
await migrateLinks(); // create tables based on previous loaded modules
await iniLinks(); // load link based on previous loaded modules
await iniLinks(undefined, [
{
serviceName: "product_custom_translation_service_link",
isLink: true,
databaseConfig: {
tableName: "product_transalations",
},
alias: [
{
name: "translations",
},
],
primaryKeys: ["id", "product_id", "translation_id"],
relationships: [
{
serviceName: Modules.PRODUCT,
primaryKey: "id",
foreignKey: "product_id",
alias: "product",
},
{
serviceName: "custom_translation_service",
primaryKey: "id",
foreignKey: "translation_id",
alias: "transalation",
deleteCascade: true,
},
],
extends: [
{
serviceName: Modules.PRODUCT,
relationship: {
serviceName: "product_custom_translation_service_link",
primaryKey: "product_id",
foreignKey: "id",
alias: "translations",
isList: true,
},
},
{
serviceName: "custom_translation_service",
relationship: {
serviceName: "product_custom_translation_service_link",
primaryKey: "product_id",
foreignKey: "id",
alias: "product_link",
},
},
],
},
]); // custom links
```
Remote Link
```typescript
import { RemoteLink, Modules } from "@medusajs/modules-sdk";
// [...] initialize modules and links
const remoteLink = new RemoteLink();
// upsert the relationship
await remoteLink.create({ // one (object) or many (array)
[Modules.PRODUCT]: {
variant_id: "var_abc",
},
[Modules.INVENTORY]: {
inventory_item_id: "iitem_abc",
},
data: { // optional additional fields
required_quantity: 5
}
});
// dismiss (doesn't cascade)
await remoteLink.dismiss({ // one (object) or many (array)
[Modules.PRODUCT]: {
variant_id: "var_abc",
},
[Modules.INVENTORY]: {
inventory_item_id: "iitem_abc",
},
});
// delete
await remoteLink.delete({
// every key is a module
[Modules.PRODUCT]: {
// every key is a linkable field
variant_id: "var_abc", // single or multiple values
},
});
// restore
await remoteLink.restore({
// every key is a module
[Modules.PRODUCT]: {
// every key is a linkable field
variant_id: "var_abc", // single or multiple values
},
});
```
Co-authored-by: Riqwan Thamir <5105988+riqwan@users.noreply.github.com>
This commit is contained in:
co-authored by
Riqwan Thamir
parent
bc4c9e0d32
commit
4d16acf5f0
@@ -0,0 +1,183 @@
|
||||
import { RemoteFetchDataCallback } from "@medusajs/orchestration"
|
||||
import {
|
||||
LoadedModule,
|
||||
MODULE_RESOURCE_TYPE,
|
||||
MODULE_SCOPE,
|
||||
ModuleConfig,
|
||||
ModuleJoinerConfig,
|
||||
ModuleServiceInitializeOptions,
|
||||
RemoteJoinerQuery,
|
||||
} from "@medusajs/types"
|
||||
import {
|
||||
ContainerRegistrationKeys,
|
||||
ModulesSdkUtils,
|
||||
isObject,
|
||||
} from "@medusajs/utils"
|
||||
import { MODULE_PACKAGE_NAMES, Modules } from "./definitions"
|
||||
import { MedusaModule } from "./medusa-module"
|
||||
import { RemoteLink } from "./remote-link"
|
||||
import { RemoteQuery } from "./remote-query"
|
||||
|
||||
export type MedusaModuleConfig = (Partial<ModuleConfig> | Modules)[]
|
||||
export type SharedResources = {
|
||||
database?: ModuleServiceInitializeOptions["database"] & {
|
||||
pool?: {
|
||||
name?: string
|
||||
afterCreate?: Function
|
||||
min?: number
|
||||
max?: number
|
||||
refreshIdle?: boolean
|
||||
idleTimeoutMillis?: number
|
||||
reapIntervalMillis?: number
|
||||
returnToHead?: boolean
|
||||
priorityRange?: number
|
||||
log?: (message: string, logLevel: string) => void
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function MedusaApp({
|
||||
sharedResourcesConfig,
|
||||
modulesConfigPath,
|
||||
modulesConfig,
|
||||
linkModules,
|
||||
remoteFetchData,
|
||||
}: {
|
||||
sharedResourcesConfig?: SharedResources
|
||||
loadedModules?: LoadedModule[]
|
||||
modulesConfigPath?: string
|
||||
modulesConfig?: MedusaModuleConfig
|
||||
linkModules?: ModuleJoinerConfig | ModuleJoinerConfig[]
|
||||
remoteFetchData?: RemoteFetchDataCallback
|
||||
} = {}): Promise<{
|
||||
modules: Record<string, LoadedModule | LoadedModule[]>
|
||||
link: RemoteLink | undefined
|
||||
query: (
|
||||
query: string | RemoteJoinerQuery,
|
||||
variables?: Record<string, unknown>
|
||||
) => Promise<any>
|
||||
}> {
|
||||
const modules: MedusaModuleConfig =
|
||||
modulesConfig ??
|
||||
(await import(process.cwd() + (modulesConfigPath ?? "/modules-config")))
|
||||
.default
|
||||
|
||||
const injectedDependencies: any = {}
|
||||
|
||||
const dbData = ModulesSdkUtils.loadDatabaseConfig(
|
||||
"medusa",
|
||||
sharedResourcesConfig as ModuleServiceInitializeOptions,
|
||||
true
|
||||
)!
|
||||
const { pool } = sharedResourcesConfig?.database ?? {}
|
||||
|
||||
if (dbData?.clientUrl) {
|
||||
const { knex } = await import("knex")
|
||||
const dbConnection = knex({
|
||||
client: "pg",
|
||||
searchPath: dbData.schema || "public",
|
||||
connection: {
|
||||
connectionString: dbData.clientUrl,
|
||||
ssl: (dbData.driverOptions?.connection as any).ssl! ?? false,
|
||||
},
|
||||
pool: {
|
||||
// https://knexjs.org/guide/#pool
|
||||
...(pool ?? {}),
|
||||
min: pool?.min ?? 0,
|
||||
},
|
||||
})
|
||||
|
||||
injectedDependencies[ContainerRegistrationKeys.PG_CONNECTION] = dbConnection
|
||||
}
|
||||
|
||||
const allModules: Record<string, LoadedModule | LoadedModule[]> = {}
|
||||
|
||||
await Promise.all(
|
||||
modules.map(async (mod: Partial<ModuleConfig> | Modules) => {
|
||||
let key: Modules | string = mod as Modules
|
||||
let path: string
|
||||
let declaration: any = {}
|
||||
|
||||
if (isObject(mod)) {
|
||||
if (!mod.module) {
|
||||
throw new Error(
|
||||
`Module ${JSON.stringify(mod)} is missing module name.`
|
||||
)
|
||||
}
|
||||
|
||||
key = mod.module
|
||||
path = mod.path ?? MODULE_PACKAGE_NAMES[key]
|
||||
|
||||
declaration = { ...mod }
|
||||
delete declaration.definition
|
||||
} else {
|
||||
path = MODULE_PACKAGE_NAMES[mod as Modules]
|
||||
}
|
||||
|
||||
if (!path) {
|
||||
throw new Error(`Module ${key} is missing path.`)
|
||||
}
|
||||
|
||||
declaration.scope ??= MODULE_SCOPE.INTERNAL
|
||||
|
||||
if (
|
||||
declaration.scope === MODULE_SCOPE.INTERNAL &&
|
||||
!declaration.resources
|
||||
) {
|
||||
declaration.resources = MODULE_RESOURCE_TYPE.SHARED
|
||||
}
|
||||
|
||||
const loaded = (await MedusaModule.bootstrap(
|
||||
key,
|
||||
path,
|
||||
declaration,
|
||||
undefined,
|
||||
injectedDependencies,
|
||||
isObject(mod) ? mod.definition : undefined
|
||||
)) as LoadedModule
|
||||
|
||||
if (allModules[key] && !Array.isArray(allModules[key])) {
|
||||
allModules[key] = []
|
||||
}
|
||||
|
||||
if (allModules[key]) {
|
||||
;(allModules[key] as LoadedModule[]).push(loaded[key])
|
||||
} else {
|
||||
allModules[key] = loaded[key]
|
||||
}
|
||||
|
||||
return loaded
|
||||
})
|
||||
)
|
||||
|
||||
let link: RemoteLink | undefined = undefined
|
||||
let query: (
|
||||
query: string | RemoteJoinerQuery,
|
||||
variables?: Record<string, unknown>
|
||||
) => Promise<any>
|
||||
|
||||
try {
|
||||
const { initialize: initializeLinks } = await import(
|
||||
"@medusajs/link-modules" as string
|
||||
)
|
||||
await initializeLinks({}, linkModules, injectedDependencies)
|
||||
|
||||
link = new RemoteLink()
|
||||
} catch (err) {
|
||||
console.warn("Error initializing link modules.", err)
|
||||
}
|
||||
|
||||
const remoteQuery = new RemoteQuery(undefined, remoteFetchData)
|
||||
query = async (
|
||||
query: string | RemoteJoinerQuery,
|
||||
variables?: Record<string, unknown>
|
||||
) => {
|
||||
return await remoteQuery.query(query, variables)
|
||||
}
|
||||
|
||||
return {
|
||||
modules: allModules,
|
||||
link,
|
||||
query,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user