@medusajs/link-modules 0.1.0-canary-20230831100806

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/definitions/index.d.ts +2 -0
  2. package/dist/definitions/index.js +18 -0
  3. package/dist/definitions/inventory-level-stock-location.d.ts +2 -0
  4. package/dist/definitions/inventory-level-stock-location.js +20 -0
  5. package/dist/definitions/product-variant-inventory-item.d.ts +2 -0
  6. package/dist/definitions/product-variant-inventory-item.js +67 -0
  7. package/dist/index.d.ts +4 -0
  8. package/dist/index.js +20 -0
  9. package/dist/initialize/index.d.ts +7 -0
  10. package/dist/initialize/index.js +124 -0
  11. package/dist/initialize/module-definition.d.ts +2 -0
  12. package/dist/initialize/module-definition.js +18 -0
  13. package/dist/links.d.ts +3 -0
  14. package/dist/links.js +8 -0
  15. package/dist/loaders/connection.d.ts +3 -0
  16. package/dist/loaders/connection.js +18 -0
  17. package/dist/loaders/container.d.ts +3 -0
  18. package/dist/loaders/container.js +22 -0
  19. package/dist/loaders/index.d.ts +6 -0
  20. package/dist/loaders/index.js +14 -0
  21. package/dist/migration/index.d.ts +2 -0
  22. package/dist/migration/index.js +52 -0
  23. package/dist/repositories/index.d.ts +2 -0
  24. package/dist/repositories/index.js +7 -0
  25. package/dist/repositories/link.d.ts +32 -0
  26. package/dist/repositories/link.js +54 -0
  27. package/dist/services/dynamic-service-class.d.ts +7 -0
  28. package/dist/services/dynamic-service-class.js +22 -0
  29. package/dist/services/index.d.ts +3 -0
  30. package/dist/services/index.js +25 -0
  31. package/dist/services/link-module-service.d.ts +33 -0
  32. package/dist/services/link-module-service.js +204 -0
  33. package/dist/services/link.d.ts +16 -0
  34. package/dist/services/link.js +121 -0
  35. package/dist/types/index.d.ts +4 -0
  36. package/dist/types/index.js +2 -0
  37. package/dist/utils/compose-link-name.d.ts +2 -0
  38. package/dist/utils/compose-link-name.js +12 -0
  39. package/dist/utils/generate-entity.d.ts +3 -0
  40. package/dist/utils/generate-entity.js +86 -0
  41. package/dist/utils/index.d.ts +4 -0
  42. package/dist/utils/index.js +28 -0
  43. package/package.json +46 -0
@@ -0,0 +1,2 @@
1
+ export * from "./inventory-level-stock-location";
2
+ export * from "./product-variant-inventory-item";
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./inventory-level-stock-location"), exports);
18
+ __exportStar(require("./product-variant-inventory-item"), exports);
@@ -0,0 +1,2 @@
1
+ import { ModuleJoinerConfig } from "@medusajs/types";
2
+ export declare const InventoryLevelStockLocation: ModuleJoinerConfig;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InventoryLevelStockLocation = void 0;
4
+ const modules_sdk_1 = require("@medusajs/modules-sdk");
5
+ exports.InventoryLevelStockLocation = {
6
+ isLink: true,
7
+ isReadOnlyLink: true,
8
+ extends: [
9
+ {
10
+ serviceName: modules_sdk_1.Modules.INVENTORY,
11
+ relationship: {
12
+ serviceName: modules_sdk_1.Modules.STOCK_LOCATION,
13
+ primaryKey: "id",
14
+ foreignKey: "location_id",
15
+ alias: "stock_locations",
16
+ isList: true,
17
+ },
18
+ },
19
+ ],
20
+ };
@@ -0,0 +1,2 @@
1
+ import { ModuleJoinerConfig } from "@medusajs/types";
2
+ export declare const ProductVariantInventoryItem: ModuleJoinerConfig;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProductVariantInventoryItem = void 0;
4
+ const modules_sdk_1 = require("@medusajs/modules-sdk");
5
+ const links_1 = require("../links");
6
+ exports.ProductVariantInventoryItem = {
7
+ serviceName: links_1.LINKS.ProductVariantInventoryItem,
8
+ isLink: true,
9
+ databaseConfig: {
10
+ tableName: "product_variant_inventory_item",
11
+ idPrefix: "pvitem",
12
+ extraFields: {
13
+ required_quantity: {
14
+ type: "integer",
15
+ defaultValue: "1",
16
+ },
17
+ },
18
+ },
19
+ alias: [
20
+ {
21
+ name: "product_variant_inventory_item",
22
+ },
23
+ {
24
+ name: "product_variant_inventory_items",
25
+ },
26
+ ],
27
+ primaryKeys: ["id", "variant_id", "inventory_item_id"],
28
+ relationships: [
29
+ {
30
+ serviceName: modules_sdk_1.Modules.PRODUCT,
31
+ primaryKey: "id",
32
+ foreignKey: "variant_id",
33
+ alias: "variant",
34
+ args: {
35
+ methodSuffix: "Variants",
36
+ },
37
+ },
38
+ {
39
+ serviceName: modules_sdk_1.Modules.INVENTORY,
40
+ primaryKey: "id",
41
+ foreignKey: "inventory_item_id",
42
+ alias: "inventory",
43
+ deleteCascade: true,
44
+ },
45
+ ],
46
+ extends: [
47
+ {
48
+ serviceName: modules_sdk_1.Modules.PRODUCT,
49
+ relationship: {
50
+ serviceName: links_1.LINKS.ProductVariantInventoryItem,
51
+ primaryKey: "variant_id",
52
+ foreignKey: "id",
53
+ alias: "inventory_items",
54
+ isList: true,
55
+ },
56
+ },
57
+ {
58
+ serviceName: modules_sdk_1.Modules.INVENTORY,
59
+ relationship: {
60
+ serviceName: links_1.LINKS.ProductVariantInventoryItem,
61
+ primaryKey: "inventory_item_id",
62
+ foreignKey: "id",
63
+ alias: "variant_link",
64
+ },
65
+ },
66
+ ],
67
+ };
@@ -0,0 +1,4 @@
1
+ export * from "./initialize";
2
+ export * from "./types";
3
+ export * from "./loaders";
4
+ export * from "./services";
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./initialize"), exports);
18
+ __exportStar(require("./types"), exports);
19
+ __exportStar(require("./loaders"), exports);
20
+ __exportStar(require("./services"), exports);
@@ -0,0 +1,7 @@
1
+ import { InternalModuleDeclaration } from "@medusajs/modules-sdk";
2
+ import { ExternalModuleDeclaration, ILinkModule, LoaderOptions, ModuleJoinerConfig, ModuleServiceInitializeCustomDataLayerOptions, ModuleServiceInitializeOptions } from "@medusajs/types";
3
+ import { InitializeModuleInjectableDependencies } from "../types";
4
+ export declare const initialize: (options?: ModuleServiceInitializeOptions | ModuleServiceInitializeCustomDataLayerOptions | ExternalModuleDeclaration | InternalModuleDeclaration, modulesDefinition?: ModuleJoinerConfig[], injectedDependencies?: InitializeModuleInjectableDependencies) => Promise<{
5
+ [link: string]: ILinkModule;
6
+ }>;
7
+ export declare function runMigrations({ options, logger, }: Omit<LoaderOptions<ModuleServiceInitializeOptions>, "container">, modulesDefinition?: ModuleJoinerConfig[]): Promise<void>;
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.runMigrations = exports.initialize = void 0;
27
+ const modules_sdk_1 = require("@medusajs/modules-sdk");
28
+ const types_1 = require("@medusajs/types");
29
+ const utils_1 = require("@medusajs/utils");
30
+ const linkDefinitions = __importStar(require("../definitions"));
31
+ const migration_1 = require("../migration");
32
+ const utils_2 = require("../utils");
33
+ const module_definition_1 = require("./module-definition");
34
+ const initialize = async (options, modulesDefinition, injectedDependencies) => {
35
+ const allLinks = {};
36
+ const modulesLoadedKeys = modules_sdk_1.MedusaModule.getLoadedModules().map((mod) => Object.keys(mod)[0]);
37
+ const allLinksToLoad = Object.values(linkDefinitions).concat(modulesDefinition ?? []);
38
+ for (const linkDefinition of allLinksToLoad) {
39
+ const definition = JSON.parse(JSON.stringify(linkDefinition));
40
+ const [primary, foreign] = definition.relationships ?? [];
41
+ if (definition.relationships?.length !== 2 && !definition.isReadOnlyLink) {
42
+ throw new Error(`Link module ${definition.serviceName} can only link 2 modules.`);
43
+ }
44
+ else if (foreign?.foreignKey?.split(",").length > 1 &&
45
+ !definition.isReadOnlyLink) {
46
+ throw new Error(`Foreign key cannot be a composed key.`);
47
+ }
48
+ const serviceKey = !definition.isReadOnlyLink
49
+ ? (0, utils_1.lowerCaseFirst)(definition.serviceName ??
50
+ (0, utils_2.composeLinkName)(primary.serviceName, primary.foreignKey, foreign.serviceName, foreign.foreignKey))
51
+ : (0, utils_1.simpleHash)(JSON.stringify(definition.extends));
52
+ if (modulesLoadedKeys.includes(serviceKey)) {
53
+ continue;
54
+ }
55
+ else if (serviceKey in allLinks) {
56
+ throw new Error(`Link module ${serviceKey} already defined.`);
57
+ }
58
+ if (definition.isReadOnlyLink) {
59
+ const extended = [];
60
+ for (const extension of definition.extends ?? []) {
61
+ if (modulesLoadedKeys.includes(extension.serviceName) &&
62
+ modulesLoadedKeys.includes(extension.relationship.serviceName)) {
63
+ extended.push(extension);
64
+ }
65
+ }
66
+ definition.extends = extended;
67
+ if (extended.length === 0) {
68
+ continue;
69
+ }
70
+ }
71
+ else if (!modulesLoadedKeys.includes(primary.serviceName) ||
72
+ !modulesLoadedKeys.includes(foreign.serviceName)) {
73
+ // TODO: This should be uncommented when all modules are done
74
+ // continue
75
+ }
76
+ const moduleDefinition = (0, module_definition_1.getLinkModuleDefinition)(definition, primary, foreign);
77
+ const linkModuleDefinition = {
78
+ key: serviceKey,
79
+ registrationName: serviceKey,
80
+ label: serviceKey,
81
+ defaultModuleDeclaration: {
82
+ scope: types_1.MODULE_SCOPE.INTERNAL,
83
+ resources: injectedDependencies?.[utils_1.ContainerRegistrationKeys.PG_CONNECTION]
84
+ ? types_1.MODULE_RESOURCE_TYPE.SHARED
85
+ : types_1.MODULE_RESOURCE_TYPE.ISOLATED,
86
+ },
87
+ };
88
+ const loaded = await modules_sdk_1.MedusaModule.bootstrapLink(linkModuleDefinition, options, moduleDefinition, injectedDependencies);
89
+ allLinks[serviceKey] = Object.values(loaded)[0];
90
+ }
91
+ return allLinks;
92
+ };
93
+ exports.initialize = initialize;
94
+ async function runMigrations({ options, logger, }, modulesDefinition) {
95
+ const modulesLoadedKeys = modules_sdk_1.MedusaModule.getLoadedModules().map((mod) => Object.keys(mod)[0]);
96
+ const allLinksToLoad = Object.values(linkDefinitions).concat(modulesDefinition ?? []);
97
+ const allLinks = new Set();
98
+ for (const definition of allLinksToLoad) {
99
+ if (definition.isReadOnlyLink) {
100
+ continue;
101
+ }
102
+ if (definition.relationships?.length !== 2) {
103
+ throw new Error(`Link module ${definition.serviceName} must have 2 relationships.`);
104
+ }
105
+ const [primary, foreign] = definition.relationships ?? [];
106
+ const serviceKey = (0, utils_1.lowerCaseFirst)(definition.serviceName ??
107
+ (0, utils_2.composeLinkName)(primary.serviceName, primary.foreignKey, foreign.serviceName, foreign.foreignKey));
108
+ if (modulesLoadedKeys.includes(serviceKey)) {
109
+ continue;
110
+ }
111
+ else if (allLinks.has(serviceKey)) {
112
+ throw new Error(`Link module ${serviceKey} already exists.`);
113
+ }
114
+ allLinks.add(serviceKey);
115
+ if (!modulesLoadedKeys.includes(primary.serviceName) ||
116
+ !modulesLoadedKeys.includes(foreign.serviceName)) {
117
+ // TODO: This should be uncommented when all modules are done
118
+ // continue
119
+ }
120
+ const migrate = (0, migration_1.getMigration)(definition, serviceKey, primary, foreign);
121
+ await migrate({ options, logger });
122
+ }
123
+ }
124
+ exports.runMigrations = runMigrations;
@@ -0,0 +1,2 @@
1
+ import { JoinerRelationship, ModuleExports, ModuleJoinerConfig } from "@medusajs/types";
2
+ export declare function getLinkModuleDefinition(joinerConfig: ModuleJoinerConfig, primary: JoinerRelationship, foreign: JoinerRelationship): ModuleExports;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getLinkModuleDefinition = void 0;
4
+ const _services_1 = require("../services");
5
+ const loaders_1 = require("../loaders");
6
+ function getLinkModuleDefinition(joinerConfig, primary, foreign) {
7
+ return {
8
+ service: joinerConfig.isReadOnlyLink
9
+ ? (0, _services_1.getReadOnlyModuleService)(joinerConfig)
10
+ : (0, _services_1.getModuleService)(joinerConfig),
11
+ loaders: (0, loaders_1.getLoaders)({
12
+ joinerConfig,
13
+ primary,
14
+ foreign,
15
+ }),
16
+ };
17
+ }
18
+ exports.getLinkModuleDefinition = getLinkModuleDefinition;
@@ -0,0 +1,3 @@
1
+ export declare const LINKS: {
2
+ ProductVariantInventoryItem: string;
3
+ };
package/dist/links.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LINKS = void 0;
4
+ const modules_sdk_1 = require("@medusajs/modules-sdk");
5
+ const utils_1 = require("./utils");
6
+ exports.LINKS = {
7
+ ProductVariantInventoryItem: (0, utils_1.composeLinkName)(modules_sdk_1.Modules.PRODUCT, "variant_id", modules_sdk_1.Modules.INVENTORY, "inventory_item_id"),
8
+ };
@@ -0,0 +1,3 @@
1
+ import { InternalModuleDeclaration, LoaderOptions, ModuleServiceInitializeCustomDataLayerOptions, ModuleServiceInitializeOptions } from "@medusajs/modules-sdk";
2
+ import { EntitySchema } from "@mikro-orm/core";
3
+ export declare function connectionLoader(entity: EntitySchema): ({ options, container, logger, }: LoaderOptions<ModuleServiceInitializeOptions | ModuleServiceInitializeCustomDataLayerOptions>, moduleDeclaration?: InternalModuleDeclaration) => Promise<void>;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.connectionLoader = void 0;
4
+ const utils_1 = require("@medusajs/utils");
5
+ function connectionLoader(entity) {
6
+ return async ({ options, container, logger, }, moduleDeclaration) => {
7
+ const pathToMigrations = __dirname + "/../migrations";
8
+ await utils_1.ModulesSdkUtils.mikroOrmConnectionLoader({
9
+ entities: [entity],
10
+ container,
11
+ options,
12
+ moduleDeclaration,
13
+ logger,
14
+ pathToMigrations,
15
+ });
16
+ };
17
+ }
18
+ exports.connectionLoader = connectionLoader;
@@ -0,0 +1,3 @@
1
+ import { LoaderOptions } from "@medusajs/modules-sdk";
2
+ import { InternalModuleDeclaration, ModuleJoinerConfig, ModulesSdkTypes } from "@medusajs/types";
3
+ export declare function containerLoader(entity: any, joinerConfig: ModuleJoinerConfig): ({ options, container, }: LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions>, moduleDeclaration?: InternalModuleDeclaration) => Promise<void>;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.containerLoader = void 0;
4
+ const _repositories_1 = require("../repositories");
5
+ const _services_1 = require("../services");
6
+ const awilix_1 = require("awilix");
7
+ function containerLoader(entity, joinerConfig) {
8
+ return async ({ options, container, }, moduleDeclaration) => {
9
+ const [primary, foreign] = joinerConfig.relationships;
10
+ container.register({
11
+ joinerConfig: (0, awilix_1.asValue)(joinerConfig),
12
+ primaryKey: (0, awilix_1.asValue)(primary.foreignKey.split(",")),
13
+ foreignKey: (0, awilix_1.asValue)(foreign.foreignKey),
14
+ extraFields: (0, awilix_1.asValue)(Object.keys(joinerConfig.databaseConfig?.extraFields || {})),
15
+ linkModuleService: (0, awilix_1.asClass)((0, _services_1.getModuleService)(joinerConfig)).singleton(),
16
+ linkService: (0, awilix_1.asClass)(_services_1.LinkService).singleton(),
17
+ baseRepository: (0, awilix_1.asClass)(_repositories_1.BaseRepository).singleton(),
18
+ linkRepository: (0, awilix_1.asClass)((0, _repositories_1.getLinkRepository)(entity)).singleton(),
19
+ });
20
+ };
21
+ }
22
+ exports.containerLoader = containerLoader;
@@ -0,0 +1,6 @@
1
+ import { JoinerRelationship, ModuleJoinerConfig, ModuleLoaderFunction } from "@medusajs/types";
2
+ export declare function getLoaders({ joinerConfig, primary, foreign, }: {
3
+ joinerConfig: ModuleJoinerConfig;
4
+ primary: JoinerRelationship;
5
+ foreign: JoinerRelationship;
6
+ }): ModuleLoaderFunction[];
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getLoaders = void 0;
4
+ const utils_1 = require("../utils");
5
+ const connection_1 = require("./connection");
6
+ const container_1 = require("./container");
7
+ function getLoaders({ joinerConfig, primary, foreign, }) {
8
+ if (joinerConfig.isReadOnlyLink) {
9
+ return [];
10
+ }
11
+ const entity = (0, utils_1.generateEntity)(joinerConfig, primary, foreign);
12
+ return [(0, connection_1.connectionLoader)(entity), (0, container_1.containerLoader)(entity, joinerConfig)];
13
+ }
14
+ exports.getLoaders = getLoaders;
@@ -0,0 +1,2 @@
1
+ import { JoinerRelationship, LoaderOptions, ModuleJoinerConfig, ModuleServiceInitializeOptions } from "@medusajs/types";
2
+ export declare function getMigration(joinerConfig: ModuleJoinerConfig, serviceName: string, primary: JoinerRelationship, foreign: JoinerRelationship): ({ options, logger, }?: Pick<LoaderOptions<ModuleServiceInitializeOptions>, "options" | "logger">) => Promise<void>;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMigration = void 0;
4
+ const utils_1 = require("../utils");
5
+ const utils_2 = require("@medusajs/utils");
6
+ function getMigration(joinerConfig, serviceName, primary, foreign) {
7
+ return async function runMigrations({ options, logger, } = {}) {
8
+ logger ?? (logger = console);
9
+ const dbData = utils_2.ModulesSdkUtils.loadDatabaseConfig("link_modules", options);
10
+ const entity = (0, utils_1.generateEntity)(joinerConfig, primary, foreign);
11
+ const pathToMigrations = __dirname + "/../migrations";
12
+ const orm = await utils_2.DALUtils.mikroOrmCreateConnection(dbData, [entity], pathToMigrations);
13
+ const tableName = entity.meta.collection;
14
+ let hasTable = false;
15
+ try {
16
+ await orm.em.getConnection().execute(`SELECT 1 FROM ${tableName} LIMIT 0`);
17
+ hasTable = true;
18
+ }
19
+ catch { }
20
+ const generator = orm.getSchemaGenerator();
21
+ if (hasTable) {
22
+ const updateSql = await generator.getUpdateSchemaSQL();
23
+ const entityUpdates = updateSql
24
+ .split(";")
25
+ .map((sql) => sql.trim())
26
+ .filter((sql) => sql.toLowerCase().includes(`alter table "${tableName.toLowerCase()}"`));
27
+ if (entityUpdates.length > 0) {
28
+ try {
29
+ await generator.execute(entityUpdates.join(";"));
30
+ logger.info(`Link module "${serviceName}" migration executed`);
31
+ }
32
+ catch (error) {
33
+ logger.error(`Link module "${serviceName}" migration failed to run - Error: ${error}`);
34
+ }
35
+ }
36
+ else {
37
+ logger.info(`Skipping "${tableName}" migration.`);
38
+ }
39
+ }
40
+ else {
41
+ try {
42
+ await generator.createSchema();
43
+ logger.info(`Link module "${serviceName}" migration executed`);
44
+ }
45
+ catch (error) {
46
+ logger.error(`Link module "${serviceName}" migration failed to run - Error: ${error}`);
47
+ }
48
+ }
49
+ await orm.close();
50
+ };
51
+ }
52
+ exports.getMigration = getMigration;
@@ -0,0 +1,2 @@
1
+ export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils";
2
+ export { getLinkRepository } from "./link";
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getLinkRepository = exports.BaseRepository = void 0;
4
+ var utils_1 = require("@medusajs/utils");
5
+ Object.defineProperty(exports, "BaseRepository", { enumerable: true, get: function () { return utils_1.MikroOrmBaseRepository; } });
6
+ var link_1 = require("./link");
7
+ Object.defineProperty(exports, "getLinkRepository", { enumerable: true, get: function () { return link_1.getLinkRepository; } });
@@ -0,0 +1,32 @@
1
+ import { Context, FindOptions, ModuleJoinerConfig } from "@medusajs/types";
2
+ import { EntitySchema } from "@mikro-orm/core";
3
+ import { SqlEntityManager } from "@mikro-orm/postgresql";
4
+ export declare function getLinkRepository(model: EntitySchema): {
5
+ new ({ manager, joinerConfig, }: {
6
+ manager: SqlEntityManager;
7
+ joinerConfig: ModuleJoinerConfig;
8
+ }): {
9
+ readonly manager_: SqlEntityManager;
10
+ readonly model_: EntitySchema;
11
+ readonly joinerConfig_: ModuleJoinerConfig;
12
+ find(findOptions?: FindOptions<unknown>, context?: Context): Promise<unknown[]>;
13
+ findAndCount(findOptions?: FindOptions<object>, context?: Context): Promise<[object[], number]>;
14
+ delete(data: any, context?: Context): Promise<void>;
15
+ create(data: object[], context?: Context): Promise<object[]>;
16
+ update(data: unknown[], context?: Context | undefined): Promise<object[]>;
17
+ softDelete(idsOrFilter: string[] | {
18
+ [x: string]: any;
19
+ }, { transactionManager: manager }?: Context | undefined): Promise<[object[], Record<string, unknown[]>]>;
20
+ restore(idsOrFilter: string[] | {
21
+ [x: string]: any;
22
+ }, { transactionManager: manager }?: Context | undefined): Promise<[object[], Record<string, unknown[]>]>;
23
+ getFreshManager<TManager = unknown>(): TManager;
24
+ getActiveManager<TManager_1 = unknown>({ transactionManager, manager }?: Context | undefined): TManager_1;
25
+ transaction<TManager_2 = unknown>(task: (transactionManager: TManager_2) => Promise<any>, options?: {
26
+ isolationLevel?: string | undefined;
27
+ enableNestedTransactions?: boolean | undefined;
28
+ transaction?: TManager_2 | undefined;
29
+ } | undefined): Promise<any>;
30
+ serialize<TOutput extends object | object[]>(data: any, options?: any): Promise<TOutput>;
31
+ };
32
+ };
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getLinkRepository = void 0;
4
+ const core_1 = require("@mikro-orm/core");
5
+ const utils_1 = require("@medusajs/utils");
6
+ function getLinkRepository(model) {
7
+ return class LinkRepository extends utils_1.MikroOrmAbstractBaseRepository {
8
+ constructor({ manager, joinerConfig, }) {
9
+ // @ts-ignore
10
+ super(...arguments);
11
+ this.manager_ = manager;
12
+ this.model_ = model;
13
+ this.joinerConfig_ = joinerConfig;
14
+ }
15
+ async find(findOptions = { where: {} }, context = {}) {
16
+ const manager = this.getActiveManager(context);
17
+ const findOptions_ = { ...findOptions };
18
+ findOptions_.options ?? (findOptions_.options = {});
19
+ Object.assign(findOptions_.options, {
20
+ strategy: core_1.LoadStrategy.SELECT_IN,
21
+ });
22
+ return await manager.find(this.model_, findOptions_.where, findOptions_.options);
23
+ }
24
+ async findAndCount(findOptions = { where: {} }, context = {}) {
25
+ const manager = this.getActiveManager(context);
26
+ const findOptions_ = { ...findOptions };
27
+ findOptions_.options ?? (findOptions_.options = {});
28
+ Object.assign(findOptions_.options, {
29
+ strategy: core_1.LoadStrategy.SELECT_IN,
30
+ });
31
+ return await manager.findAndCount(this.model_, findOptions_.where, findOptions_.options);
32
+ }
33
+ async delete(data, context = {}) {
34
+ const filter = {};
35
+ for (const key in data) {
36
+ filter[key] = {
37
+ $in: Array.isArray(data[key]) ? data[key] : [data[key]],
38
+ };
39
+ }
40
+ const manager = this.getActiveManager(context);
41
+ await manager.nativeDelete(this.model_, data, {});
42
+ }
43
+ async create(data, context = {}) {
44
+ const manager = this.getActiveManager(context);
45
+ const links = data.map((link) => {
46
+ link.id = (0, utils_1.generateEntityId)(link.id, this.joinerConfig_.databaseConfig?.idPrefix ?? "link");
47
+ return manager.create(this.model_, link);
48
+ });
49
+ await manager.upsertMany(this.model_, links);
50
+ return links;
51
+ }
52
+ };
53
+ }
54
+ exports.getLinkRepository = getLinkRepository;
@@ -0,0 +1,7 @@
1
+ import { Constructor, ILinkModule, ModuleJoinerConfig } from "@medusajs/types";
2
+ export declare function getModuleService(joinerConfig: ModuleJoinerConfig): Constructor<ILinkModule>;
3
+ export declare function getReadOnlyModuleService(joinerConfig: ModuleJoinerConfig): {
4
+ new (): {
5
+ __joinerConfig(): ModuleJoinerConfig;
6
+ };
7
+ };
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getReadOnlyModuleService = exports.getModuleService = void 0;
4
+ const _services_1 = require(".");
5
+ function getModuleService(joinerConfig) {
6
+ const joinerConfig_ = JSON.parse(JSON.stringify(joinerConfig));
7
+ delete joinerConfig_.databaseConfig;
8
+ return class LinkService extends _services_1.LinkModuleService {
9
+ __joinerConfig() {
10
+ return joinerConfig_;
11
+ }
12
+ };
13
+ }
14
+ exports.getModuleService = getModuleService;
15
+ function getReadOnlyModuleService(joinerConfig) {
16
+ return class ReadOnlyLinkService {
17
+ __joinerConfig() {
18
+ return joinerConfig;
19
+ }
20
+ };
21
+ }
22
+ exports.getReadOnlyModuleService = getReadOnlyModuleService;
@@ -0,0 +1,3 @@
1
+ export * from "./dynamic-service-class";
2
+ export { default as LinkService } from "./link";
3
+ export { default as LinkModuleService } from "./link-module-service";
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.LinkModuleService = exports.LinkService = void 0;
21
+ __exportStar(require("./dynamic-service-class"), exports);
22
+ var link_1 = require("./link");
23
+ Object.defineProperty(exports, "LinkService", { enumerable: true, get: function () { return __importDefault(link_1).default; } });
24
+ var link_module_service_1 = require("./link-module-service");
25
+ Object.defineProperty(exports, "LinkModuleService", { enumerable: true, get: function () { return __importDefault(link_module_service_1).default; } });
@@ -0,0 +1,33 @@
1
+ import { Context, DAL, FindConfig, ILinkModule, InternalModuleDeclaration, ModuleJoinerConfig, RestoreReturn, SoftDeleteReturn } from "@medusajs/types";
2
+ import { LinkService } from ".";
3
+ type InjectedDependencies = {
4
+ baseRepository: DAL.RepositoryService;
5
+ linkService: LinkService<any>;
6
+ primaryKey: string | string[];
7
+ foreignKey: string;
8
+ extraFields: string[];
9
+ };
10
+ export default class LinkModuleService<TLink> implements ILinkModule {
11
+ readonly moduleDeclaration: InternalModuleDeclaration;
12
+ protected baseRepository_: DAL.RepositoryService;
13
+ protected readonly linkService_: LinkService<TLink>;
14
+ protected primaryKey_: string[];
15
+ protected foreignKey_: string;
16
+ protected extraFields_: string[];
17
+ constructor({ baseRepository, linkService, primaryKey, foreignKey, extraFields, }: InjectedDependencies, moduleDeclaration: InternalModuleDeclaration);
18
+ __joinerConfig(): ModuleJoinerConfig;
19
+ private buildData;
20
+ private isValidKeyName;
21
+ private validateFields;
22
+ retrieve(primaryKeyData: string | string[], foreignKeyData: string, sharedContext?: Context): Promise<unknown>;
23
+ list(filters?: Record<string, unknown>, config?: FindConfig<unknown>, sharedContext?: Context): Promise<unknown[]>;
24
+ listAndCount(filters?: Record<string, unknown>, config?: FindConfig<unknown>, sharedContext?: Context): Promise<[unknown[], number]>;
25
+ create(primaryKeyOrBulkData: string | string[] | [string | string[], string, Record<string, unknown>][], foreignKeyData?: string, extraFields?: Record<string, unknown>, sharedContext?: Context): Promise<object[]>;
26
+ dismiss(primaryKeyOrBulkData: string | string[] | [string | string[], string][], foreignKeyData?: string, sharedContext?: Context): Promise<object[]>;
27
+ delete(data: any, sharedContext?: Context): Promise<void>;
28
+ softDelete(data: any, { returnLinkableKeys }?: SoftDeleteReturn, sharedContext?: Context): Promise<Record<string, unknown[]> | void>;
29
+ protected softDelete_(data: any, sharedContext?: Context): Promise<[string[], Record<string, string[]>]>;
30
+ restore(data: any, { returnLinkableKeys }?: RestoreReturn, sharedContext?: Context): Promise<Record<string, unknown[]> | void>;
31
+ restore_(data: any, sharedContext?: Context): Promise<[string[], Record<string, string[]>]>;
32
+ }
33
+ export {};
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const utils_1 = require("@medusajs/utils");
16
+ const utils_2 = require("../utils");
17
+ class LinkModuleService {
18
+ constructor({ baseRepository, linkService, primaryKey, foreignKey, extraFields, }, moduleDeclaration) {
19
+ this.moduleDeclaration = moduleDeclaration;
20
+ this.baseRepository_ = baseRepository;
21
+ this.linkService_ = linkService;
22
+ this.primaryKey_ = !Array.isArray(primaryKey) ? [primaryKey] : primaryKey;
23
+ this.foreignKey_ = foreignKey;
24
+ this.extraFields_ = extraFields;
25
+ }
26
+ __joinerConfig() {
27
+ return {};
28
+ }
29
+ buildData(primaryKeyData, foreignKeyData, extra = {}) {
30
+ if (this.primaryKey_.length > 1) {
31
+ if (!Array.isArray(primaryKeyData) ||
32
+ primaryKeyData.length !== this.primaryKey_.length) {
33
+ throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Primary key data must be an array ${this.primaryKey_.length} values`);
34
+ }
35
+ }
36
+ const pk = this.primaryKey_.join(",");
37
+ return {
38
+ [pk]: primaryKeyData,
39
+ [this.foreignKey_]: foreignKeyData,
40
+ ...extra,
41
+ };
42
+ }
43
+ isValidKeyName(name) {
44
+ return this.primaryKey_.concat(this.foreignKey_).includes(name);
45
+ }
46
+ validateFields(data) {
47
+ const keys = Object.keys(data);
48
+ if (!keys.every((k) => this.isValidKeyName(k))) {
49
+ throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Invalid field name provided. Valid field names are ${this.primaryKey_.concat(this.foreignKey_)}`);
50
+ }
51
+ }
52
+ async retrieve(primaryKeyData, foreignKeyData, sharedContext = {}) {
53
+ const filter = this.buildData(primaryKeyData, foreignKeyData);
54
+ const queryOptions = utils_1.ModulesSdkUtils.buildQuery(filter);
55
+ const entry = await this.linkService_.list(queryOptions, {}, sharedContext);
56
+ if (!entry?.length) {
57
+ const pk = this.primaryKey_.join(",");
58
+ const errMessage = `${pk}[${primaryKeyData}] and ${this.foreignKey_}[${foreignKeyData}]`;
59
+ throw new utils_1.MedusaError(utils_1.MedusaError.Types.NOT_FOUND, `Entry ${errMessage} was not found`);
60
+ }
61
+ return entry[0];
62
+ }
63
+ async list(filters = {}, config = {}, sharedContext = {}) {
64
+ const rows = await this.linkService_.list(filters, config, sharedContext);
65
+ return await this.baseRepository_.serialize(rows);
66
+ }
67
+ async listAndCount(filters = {}, config = {}, sharedContext = {}) {
68
+ const [rows, count] = await this.linkService_.listAndCount(filters, config, sharedContext);
69
+ return [await this.baseRepository_.serialize(rows), count];
70
+ }
71
+ async create(primaryKeyOrBulkData, foreignKeyData, extraFields, sharedContext = {}) {
72
+ const data = [];
73
+ if (foreignKeyData === undefined && Array.isArray(primaryKeyOrBulkData)) {
74
+ for (const [primaryKey, foreignKey, extra] of primaryKeyOrBulkData) {
75
+ data.push(this.buildData(primaryKey, foreignKey, extra));
76
+ }
77
+ }
78
+ else {
79
+ data.push(this.buildData(primaryKeyOrBulkData, foreignKeyData, extraFields));
80
+ }
81
+ const links = await this.linkService_.create(data, sharedContext);
82
+ return await this.baseRepository_.serialize(links);
83
+ }
84
+ async dismiss(primaryKeyOrBulkData, foreignKeyData, sharedContext = {}) {
85
+ const data = [];
86
+ if (foreignKeyData === undefined && Array.isArray(primaryKeyOrBulkData)) {
87
+ for (const [primaryKey, foreignKey] of primaryKeyOrBulkData) {
88
+ data.push(this.buildData(primaryKey, foreignKey));
89
+ }
90
+ }
91
+ else {
92
+ data.push(this.buildData(primaryKeyOrBulkData, foreignKeyData));
93
+ }
94
+ const links = await this.linkService_.dismiss(data, sharedContext);
95
+ return await this.baseRepository_.serialize(links);
96
+ }
97
+ async delete(data, sharedContext = {}) {
98
+ this.validateFields(data);
99
+ await this.linkService_.delete(data, sharedContext);
100
+ }
101
+ async softDelete(data, { returnLinkableKeys } = {}, sharedContext = {}) {
102
+ this.validateFields(data);
103
+ let [, cascadedEntitiesMap] = await this.softDelete_(data, sharedContext);
104
+ const pk = this.primaryKey_.join(",");
105
+ const entityNameToLinkableKeysMap = {
106
+ LinkModel: [
107
+ { mapTo: pk, valueFrom: pk },
108
+ { mapTo: this.foreignKey_, valueFrom: this.foreignKey_ },
109
+ ],
110
+ };
111
+ let mappedCascadedEntitiesMap;
112
+ if (returnLinkableKeys) {
113
+ // Map internal table/column names to their respective external linkable keys
114
+ // eg: product.id = product_id, variant.id = variant_id
115
+ mappedCascadedEntitiesMap = (0, utils_1.mapObjectTo)(cascadedEntitiesMap, entityNameToLinkableKeysMap, {
116
+ pick: returnLinkableKeys,
117
+ });
118
+ }
119
+ return mappedCascadedEntitiesMap ? mappedCascadedEntitiesMap : void 0;
120
+ }
121
+ async softDelete_(data, sharedContext = {}) {
122
+ return await this.linkService_.softDelete(data, sharedContext);
123
+ }
124
+ async restore(data, { returnLinkableKeys } = {}, sharedContext = {}) {
125
+ this.validateFields(data);
126
+ let [, cascadedEntitiesMap] = await this.restore_(data, sharedContext);
127
+ const pk = this.primaryKey_.join(",");
128
+ const entityNameToLinkableKeysMap = {
129
+ LinkModel: [
130
+ { mapTo: pk, valueFrom: pk },
131
+ { mapTo: this.foreignKey_, valueFrom: this.foreignKey_ },
132
+ ],
133
+ };
134
+ let mappedCascadedEntitiesMap;
135
+ if (returnLinkableKeys) {
136
+ // Map internal table/column names to their respective external linkable keys
137
+ // eg: product.id = product_id, variant.id = variant_id
138
+ mappedCascadedEntitiesMap = (0, utils_1.mapObjectTo)(cascadedEntitiesMap, entityNameToLinkableKeysMap, {
139
+ pick: returnLinkableKeys,
140
+ });
141
+ }
142
+ return mappedCascadedEntitiesMap ? mappedCascadedEntitiesMap : void 0;
143
+ }
144
+ async restore_(data, sharedContext = {}) {
145
+ return await this.linkService_.restore(data, sharedContext);
146
+ }
147
+ }
148
+ exports.default = LinkModuleService;
149
+ __decorate([
150
+ (0, utils_1.InjectManager)("baseRepository_"),
151
+ __param(2, (0, utils_1.MedusaContext)()),
152
+ __metadata("design:type", Function),
153
+ __metadata("design:paramtypes", [Object, String, Object]),
154
+ __metadata("design:returntype", Promise)
155
+ ], LinkModuleService.prototype, "retrieve", null);
156
+ __decorate([
157
+ (0, utils_1.InjectManager)("baseRepository_"),
158
+ __param(2, (0, utils_1.MedusaContext)()),
159
+ __metadata("design:type", Function),
160
+ __metadata("design:paramtypes", [Object, Object, Object]),
161
+ __metadata("design:returntype", Promise)
162
+ ], LinkModuleService.prototype, "list", null);
163
+ __decorate([
164
+ (0, utils_1.InjectManager)("baseRepository_"),
165
+ __param(2, (0, utils_1.MedusaContext)()),
166
+ __metadata("design:type", Function),
167
+ __metadata("design:paramtypes", [Object, Object, Object]),
168
+ __metadata("design:returntype", Promise)
169
+ ], LinkModuleService.prototype, "listAndCount", null);
170
+ __decorate([
171
+ (0, utils_1.InjectTransactionManager)(utils_2.shouldForceTransaction, "baseRepository_"),
172
+ __param(3, (0, utils_1.MedusaContext)()),
173
+ __metadata("design:type", Function),
174
+ __metadata("design:paramtypes", [Object, String, Object, Object]),
175
+ __metadata("design:returntype", Promise)
176
+ ], LinkModuleService.prototype, "create", null);
177
+ __decorate([
178
+ (0, utils_1.InjectTransactionManager)(utils_2.shouldForceTransaction, "baseRepository_"),
179
+ __param(2, (0, utils_1.MedusaContext)()),
180
+ __metadata("design:type", Function),
181
+ __metadata("design:paramtypes", [Object, String, Object]),
182
+ __metadata("design:returntype", Promise)
183
+ ], LinkModuleService.prototype, "dismiss", null);
184
+ __decorate([
185
+ (0, utils_1.InjectTransactionManager)(utils_2.shouldForceTransaction, "baseRepository_"),
186
+ __param(1, (0, utils_1.MedusaContext)()),
187
+ __metadata("design:type", Function),
188
+ __metadata("design:paramtypes", [Object, Object]),
189
+ __metadata("design:returntype", Promise)
190
+ ], LinkModuleService.prototype, "delete", null);
191
+ __decorate([
192
+ (0, utils_1.InjectTransactionManager)(utils_2.shouldForceTransaction, "baseRepository_"),
193
+ __param(1, (0, utils_1.MedusaContext)()),
194
+ __metadata("design:type", Function),
195
+ __metadata("design:paramtypes", [Object, Object]),
196
+ __metadata("design:returntype", Promise)
197
+ ], LinkModuleService.prototype, "softDelete_", null);
198
+ __decorate([
199
+ (0, utils_1.InjectTransactionManager)(utils_2.shouldForceTransaction, "baseRepository_"),
200
+ __param(1, (0, utils_1.MedusaContext)()),
201
+ __metadata("design:type", Function),
202
+ __metadata("design:paramtypes", [Object, Object]),
203
+ __metadata("design:returntype", Promise)
204
+ ], LinkModuleService.prototype, "restore_", null);
@@ -0,0 +1,16 @@
1
+ import { Context, FindConfig } from "@medusajs/types";
2
+ type InjectedDependencies = {
3
+ linkRepository: any;
4
+ };
5
+ export default class LinkService<TEntity> {
6
+ protected readonly linkRepository_: any;
7
+ constructor({ linkRepository }: InjectedDependencies);
8
+ list(filters?: unknown, config?: FindConfig<unknown>, sharedContext?: Context): Promise<TEntity[]>;
9
+ listAndCount(filters?: {}, config?: FindConfig<unknown>, sharedContext?: Context): Promise<[TEntity[], number]>;
10
+ create(data: unknown[], sharedContext?: Context): Promise<TEntity[]>;
11
+ dismiss(data: unknown[], sharedContext?: Context): Promise<TEntity[]>;
12
+ delete(data: unknown, sharedContext?: Context): Promise<void>;
13
+ softDelete(data: any, sharedContext?: Context): Promise<[string[], Record<string, string[]>]>;
14
+ restore(data: any, sharedContext?: Context): Promise<[string[], Record<string, string[]>]>;
15
+ }
16
+ export {};
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const utils_1 = require("@medusajs/utils");
16
+ const utils_2 = require("../utils");
17
+ class LinkService {
18
+ constructor({ linkRepository }) {
19
+ this.linkRepository_ = linkRepository;
20
+ }
21
+ async list(filters = {}, config = {}, sharedContext = {}) {
22
+ const queryOptions = utils_1.ModulesSdkUtils.buildQuery(filters, config);
23
+ return await this.linkRepository_.find(queryOptions, sharedContext);
24
+ }
25
+ async listAndCount(filters = {}, config = {}, sharedContext = {}) {
26
+ const queryOptions = utils_1.ModulesSdkUtils.buildQuery(filters, config);
27
+ return await this.linkRepository_.findAndCount(queryOptions, sharedContext);
28
+ }
29
+ async create(data, sharedContext = {}) {
30
+ return await this.linkRepository_.create(data, {
31
+ transactionManager: sharedContext.transactionManager,
32
+ });
33
+ }
34
+ async dismiss(data, sharedContext = {}) {
35
+ const filter = [];
36
+ for (const pair of data) {
37
+ filter.push({
38
+ $and: Object.entries(pair).map(([key, value]) => ({
39
+ [key]: value,
40
+ })),
41
+ });
42
+ }
43
+ const [rows] = await this.linkRepository_.softDelete({ $or: filter }, {
44
+ transactionManager: sharedContext.transactionManager,
45
+ });
46
+ return rows;
47
+ }
48
+ async delete(data, sharedContext = {}) {
49
+ await this.linkRepository_.delete(data, {
50
+ transactionManager: sharedContext.transactionManager,
51
+ });
52
+ }
53
+ async softDelete(data, sharedContext = {}) {
54
+ const filter = {};
55
+ for (const key in data) {
56
+ filter[key] = { $in: Array.isArray(data[key]) ? data[key] : [data[key]] };
57
+ }
58
+ return await this.linkRepository_.softDelete(filter, {
59
+ transactionManager: sharedContext.transactionManager,
60
+ });
61
+ }
62
+ async restore(data, sharedContext = {}) {
63
+ const filter = {};
64
+ for (const key in data) {
65
+ filter[key] = { $in: Array.isArray(data[key]) ? data[key] : [data[key]] };
66
+ }
67
+ return await this.linkRepository_.restore(data, {
68
+ transactionManager: sharedContext.transactionManager,
69
+ });
70
+ }
71
+ }
72
+ exports.default = LinkService;
73
+ __decorate([
74
+ (0, utils_1.InjectManager)("linkRepository_"),
75
+ __param(2, (0, utils_1.MedusaContext)()),
76
+ __metadata("design:type", Function),
77
+ __metadata("design:paramtypes", [Object, Object, Object]),
78
+ __metadata("design:returntype", Promise)
79
+ ], LinkService.prototype, "list", null);
80
+ __decorate([
81
+ (0, utils_1.InjectManager)("linkRepository_"),
82
+ __param(2, (0, utils_1.MedusaContext)()),
83
+ __metadata("design:type", Function),
84
+ __metadata("design:paramtypes", [Object, Object, Object]),
85
+ __metadata("design:returntype", Promise)
86
+ ], LinkService.prototype, "listAndCount", null);
87
+ __decorate([
88
+ (0, utils_1.InjectTransactionManager)(utils_2.doNotForceTransaction, "linkRepository_"),
89
+ __param(1, (0, utils_1.MedusaContext)()),
90
+ __metadata("design:type", Function),
91
+ __metadata("design:paramtypes", [Array, Object]),
92
+ __metadata("design:returntype", Promise)
93
+ ], LinkService.prototype, "create", null);
94
+ __decorate([
95
+ (0, utils_1.InjectTransactionManager)(utils_2.doNotForceTransaction, "linkRepository_"),
96
+ __param(1, (0, utils_1.MedusaContext)()),
97
+ __metadata("design:type", Function),
98
+ __metadata("design:paramtypes", [Array, Object]),
99
+ __metadata("design:returntype", Promise)
100
+ ], LinkService.prototype, "dismiss", null);
101
+ __decorate([
102
+ (0, utils_1.InjectTransactionManager)(utils_2.doNotForceTransaction, "linkRepository_"),
103
+ __param(1, (0, utils_1.MedusaContext)()),
104
+ __metadata("design:type", Function),
105
+ __metadata("design:paramtypes", [Object, Object]),
106
+ __metadata("design:returntype", Promise)
107
+ ], LinkService.prototype, "delete", null);
108
+ __decorate([
109
+ (0, utils_1.InjectTransactionManager)(utils_2.doNotForceTransaction, "linkRepository_"),
110
+ __param(1, (0, utils_1.MedusaContext)()),
111
+ __metadata("design:type", Function),
112
+ __metadata("design:paramtypes", [Object, Object]),
113
+ __metadata("design:returntype", Promise)
114
+ ], LinkService.prototype, "softDelete", null);
115
+ __decorate([
116
+ (0, utils_1.InjectTransactionManager)(utils_2.doNotForceTransaction, "linkRepository_"),
117
+ __param(1, (0, utils_1.MedusaContext)()),
118
+ __metadata("design:type", Function),
119
+ __metadata("design:paramtypes", [Object, Object]),
120
+ __metadata("design:returntype", Promise)
121
+ ], LinkService.prototype, "restore", null);
@@ -0,0 +1,4 @@
1
+ import { Logger } from "@medusajs/types";
2
+ export type InitializeModuleInjectableDependencies = {
3
+ logger?: Logger;
4
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ export declare const composeLinkName: (...args: any[]) => string;
2
+ export declare const composeTableName: (...args: any[]) => string;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.composeTableName = exports.composeLinkName = void 0;
4
+ const utils_1 = require("@medusajs/utils");
5
+ const composeLinkName = (...args) => {
6
+ return (0, utils_1.lowerCaseFirst)((0, utils_1.toPascalCase)((0, exports.composeTableName)(...args.concat("link"))));
7
+ };
8
+ exports.composeLinkName = composeLinkName;
9
+ const composeTableName = (...args) => {
10
+ return args.map((name) => name.replace(/(_id|Service)$/gi, "")).join("_");
11
+ };
12
+ exports.composeTableName = composeTableName;
@@ -0,0 +1,3 @@
1
+ import { JoinerRelationship, ModuleJoinerConfig } from "@medusajs/types";
2
+ import { EntitySchema } from "@mikro-orm/core";
3
+ export declare function generateEntity(joinerConfig: ModuleJoinerConfig, primary: JoinerRelationship, foreign: JoinerRelationship): EntitySchema<any, never>;
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateEntity = void 0;
4
+ const utils_1 = require("@medusajs/utils");
5
+ const core_1 = require("@mikro-orm/core");
6
+ const compose_link_name_1 = require("./compose-link-name");
7
+ function getClass(...properties) {
8
+ return class LinkModel {
9
+ constructor(...values) {
10
+ properties.forEach((name, idx) => {
11
+ this[name] = values[idx];
12
+ });
13
+ }
14
+ };
15
+ }
16
+ function generateEntity(joinerConfig, primary, foreign) {
17
+ const fieldNames = primary.foreignKey.split(",").concat(foreign.foreignKey);
18
+ const tableName = joinerConfig.databaseConfig?.tableName ??
19
+ (0, compose_link_name_1.composeTableName)(primary.serviceName, primary.foreignKey, foreign.serviceName, foreign.foreignKey);
20
+ const fields = fieldNames.reduce((acc, curr) => {
21
+ acc[curr] = {
22
+ type: "string",
23
+ nullable: false,
24
+ primary: true,
25
+ };
26
+ return acc;
27
+ }, {});
28
+ const extraFields = joinerConfig.databaseConfig?.extraFields ?? {};
29
+ for (const column in extraFields) {
30
+ fieldNames.push(column);
31
+ fields[column] = {
32
+ type: extraFields[column].type,
33
+ nullable: !!extraFields[column].nullable,
34
+ defaultRaw: extraFields[column].defaultValue,
35
+ ...(extraFields[column].options ?? {}),
36
+ };
37
+ }
38
+ const hashTableName = (0, utils_1.simpleHash)(tableName);
39
+ return new core_1.EntitySchema({
40
+ class: getClass(...fieldNames.concat("created_at", "updated_at", "deleted_at")),
41
+ tableName,
42
+ properties: {
43
+ id: {
44
+ type: "string",
45
+ nullable: false,
46
+ },
47
+ ...fields,
48
+ created_at: {
49
+ type: "Date",
50
+ nullable: false,
51
+ defaultRaw: "CURRENT_TIMESTAMP",
52
+ },
53
+ updated_at: {
54
+ type: "Date",
55
+ nullable: false,
56
+ defaultRaw: "CURRENT_TIMESTAMP",
57
+ },
58
+ deleted_at: { type: "Date", nullable: true },
59
+ },
60
+ filters: {
61
+ [utils_1.SoftDeletableFilterKey]: utils_1.mikroOrmSoftDeletableFilterOptions,
62
+ },
63
+ indexes: [
64
+ {
65
+ properties: ["id"],
66
+ name: "IDX_id_" + hashTableName,
67
+ },
68
+ {
69
+ properties: primary.foreignKey.split(","),
70
+ name: "IDX_" +
71
+ primary.foreignKey.split(",").join("_") +
72
+ "_" +
73
+ hashTableName,
74
+ },
75
+ {
76
+ properties: foreign.foreignKey,
77
+ name: "IDX_" + foreign.foreignKey + "_" + hashTableName,
78
+ },
79
+ {
80
+ properties: ["deleted_at"],
81
+ name: "IDX_deleted_at_" + hashTableName,
82
+ },
83
+ ],
84
+ });
85
+ }
86
+ exports.generateEntity = generateEntity;
@@ -0,0 +1,4 @@
1
+ export * from "./compose-link-name";
2
+ export * from "./generate-entity";
3
+ export declare function shouldForceTransaction(target: any): boolean;
4
+ export declare function doNotForceTransaction(): boolean;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.doNotForceTransaction = exports.shouldForceTransaction = void 0;
18
+ const types_1 = require("@medusajs/types");
19
+ __exportStar(require("./compose-link-name"), exports);
20
+ __exportStar(require("./generate-entity"), exports);
21
+ function shouldForceTransaction(target) {
22
+ return target.moduleDeclaration?.resources === types_1.MODULE_RESOURCE_TYPE.ISOLATED;
23
+ }
24
+ exports.shouldForceTransaction = shouldForceTransaction;
25
+ function doNotForceTransaction() {
26
+ return false;
27
+ }
28
+ exports.doNotForceTransaction = doNotForceTransaction;
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@medusajs/link-modules",
3
+ "version": "0.1.0-canary-20230831100806",
4
+ "description": "Medusa Default Link Modules Package and Definitions",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/medusajs/medusa",
13
+ "directory": "packages/link-modules"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "author": "Medusa",
19
+ "license": "MIT",
20
+ "scripts": {
21
+ "watch": "tsc --build --watch",
22
+ "watch:test": "tsc --build tsconfig.spec.json --watch",
23
+ "prepare": "cross-env NODE_ENV=production yarn run build",
24
+ "build": "rimraf dist && tsc --build && tsc-alias -p tsconfig.json",
25
+ "test": "jest --passWithNoTests --runInBand --bail --forceExit",
26
+ "test:integration": "jest --passWithNoTests"
27
+ },
28
+ "devDependencies": {
29
+ "cross-env": "^5.2.1",
30
+ "jest": "^29.6.3",
31
+ "pg-god": "^1.0.12",
32
+ "rimraf": "^5.0.1",
33
+ "ts-jest": "^29.1.1",
34
+ "ts-node": "^10.9.1",
35
+ "tsc-alias": "^1.8.6",
36
+ "typescript": "^5.1.6"
37
+ },
38
+ "dependencies": {
39
+ "@medusajs/modules-sdk": "1.10.0-canary-20230831100806",
40
+ "@medusajs/types": "1.11.0-canary-20230831100806",
41
+ "@medusajs/utils": "1.10.0-canary-20230831100806",
42
+ "@mikro-orm/core": "5.7.12",
43
+ "@mikro-orm/postgresql": "5.7.12",
44
+ "awilix": "^8.0.0"
45
+ }
46
+ }