chore(): Reorganize modules (#7210)

**What**
Move all modules to the modules directory
This commit is contained in:
Adrien de Peretti
2024-05-02 15:33:34 +00:00
committed by GitHub
parent 7a351eef09
commit 4eae25e1ef
870 changed files with 91 additions and 62 deletions
@@ -0,0 +1,6 @@
/dist
node_modules
.DS_store
.env*
.env
*.sql
@@ -0,0 +1,12 @@
# @medusajs/sales-channel
## 0.1.1
### Patch Changes
- [#6700](https://github.com/medusajs/medusa/pull/6700) [`8f8a4f9b13`](https://github.com/medusajs/medusa/commit/8f8a4f9b1353087d98f6cc75346d43a7f49901a8) Thanks [@olivermrbl](https://github.com/olivermrbl)! - chore: Version all modules to allow for initial testing
- Updated dependencies [[`1fd0457c15`](https://github.com/medusajs/medusa/commit/1fd0457c153b2ef7657c052878d8e5364e1b324a), [`9288f53327`](https://github.com/medusajs/medusa/commit/9288f53327b8ce617af92ed8d14d9459cbfeb13c), [`d4b921f3db`](https://github.com/medusajs/medusa/commit/d4b921f3dbe0a38f1565a8de759996c70798d58e), [`ac86362e81`](https://github.com/medusajs/medusa/commit/ac86362e81d8523cb8e3dfad026fc94658513018), [`e4acde1aa2`](https://github.com/medusajs/medusa/commit/e4acde1aa2eb57f07e6692fe8b61f728948b9a96), [`1a661adf3e`](https://github.com/medusajs/medusa/commit/1a661adf3ef4991aa6e237dd894b6a5c47cd4aca), [`56cbf88115`](https://github.com/medusajs/medusa/commit/56cbf88115994adea7037c3f2814f0c96af3cfc0), [`36a61658f9`](https://github.com/medusajs/medusa/commit/36a61658f969a7b19c84a1e621ad1464927cafb1), [`04a532e5ef`](https://github.com/medusajs/medusa/commit/04a532e5efabbf75b1e4155520b1da175b686ffc), [`c319edb8e0`](https://github.com/medusajs/medusa/commit/c319edb8e0ecd13d086652147667916e5abab2d8), [`0b9fcb6324`](https://github.com/medusajs/medusa/commit/0b9fcb6324eee9f2556c7e6317775fae93b12a47), [`586df9da25`](https://github.com/medusajs/medusa/commit/586df9da250e492442769f5bac2f8b3de1d46f05), [`b3d826497b`](https://github.com/medusajs/medusa/commit/b3d826497b3dae5e1b26b7924706c24fd5e87ca5), [`a86c87fe14`](https://github.com/medusajs/medusa/commit/a86c87fe1442afce9285e39255914e01012b4449), [`640eccd5dd`](https://github.com/medusajs/medusa/commit/640eccd5ddbb163e0f987ce6c772f1129c2e2632), [`8ea37d03c9`](https://github.com/medusajs/medusa/commit/8ea37d03c914a5004a3e42770668b2d1f7f8f564), [`339a946f38`](https://github.com/medusajs/medusa/commit/339a946f389033c21e05338f9dbf07d88e140533), [`ac829fc67f`](https://github.com/medusajs/medusa/commit/ac829fc67f7495b08f28e55923c59f0fd6320311), [`d9d5afc3cf`](https://github.com/medusajs/medusa/commit/d9d5afc3cfc29221d0e65bff7b78474a8fb8f31f), [`c3c4f49fc2`](https://github.com/medusajs/medusa/commit/c3c4f49fc2126f950e69e291ca939ca88a15afd3), [`9288f53327`](https://github.com/medusajs/medusa/commit/9288f53327b8ce617af92ed8d14d9459cbfeb13c), [`0d46abf0ff`](https://github.com/medusajs/medusa/commit/0d46abf0ffa4c5e03bf7d2a9cdf1db828a76bea8), [`fafde4f54d`](https://github.com/medusajs/medusa/commit/fafde4f54d3ef75a7d382e6cbf94e38b3deae99b), [`8dad2b51a2`](https://github.com/medusajs/medusa/commit/8dad2b51a26c4c3c14a6c95f70424c8bef2ad63e), [`0c705d7bd4`](https://github.com/medusajs/medusa/commit/0c705d7bd41a768c48017ae95b3c8414d96c6acb), [`a6d7070dd6`](https://github.com/medusajs/medusa/commit/a6d7070dd669c21ea19d70434d42c2f8167dc309), [`1d91b7429b`](https://github.com/medusajs/medusa/commit/1d91b7429beebd6f09d5027f7f7e1fe74ce3a8ff), [`168f02f138`](https://github.com/medusajs/medusa/commit/168f02f138ad101e1013f2c8c3f8dc19de12accf), [`1ed5f918c3`](https://github.com/medusajs/medusa/commit/1ed5f918c31794a70aca4a4e4cd83cf456593baa), [`c20eb15cd9`](https://github.com/medusajs/medusa/commit/c20eb15cd9b1bd90c8d01f68eca6f0f181cd902d), [`e5945479e0`](https://github.com/medusajs/medusa/commit/e5945479e091d9560ae3e7240306a31031ef4584), [`f5c2256286`](https://github.com/medusajs/medusa/commit/f5c22562867f412040f8bc6c55ab5de3a3735e62), [`000eb61e33`](https://github.com/medusajs/medusa/commit/000eb61e33e0302db95ee6ad1656ea9b430ed471), [`d550be3685`](https://github.com/medusajs/medusa/commit/d550be3685423218d47a20c57a5e06758f4a961a), [`62a7bcc30c`](https://github.com/medusajs/medusa/commit/62a7bcc30cbc7b234b2b51d7858439951a84edeb), [`8f8a4f9b13`](https://github.com/medusajs/medusa/commit/8f8a4f9b1353087d98f6cc75346d43a7f49901a8), [`6500f18b9b`](https://github.com/medusajs/medusa/commit/6500f18b9b80c5c9c473489e7e740d55dca74303), [`ce39b9b66e`](https://github.com/medusajs/medusa/commit/ce39b9b66e8c277ec0691ea6d0a950003be09cc1), [`a6a4b3f01a`](https://github.com/medusajs/medusa/commit/a6a4b3f01a6d2bd97b1580c59134279a1b033a5d), [`4d51f095b3`](https://github.com/medusajs/medusa/commit/4d51f095b3f98f468cefb760512563f7b77bb9cf), [`4625bd1241`](https://github.com/medusajs/medusa/commit/4625bd12416275b09c22cde4a09cb0f68df5d7c1), [`56b0b45304`](https://github.com/medusajs/medusa/commit/56b0b4530401a6ec5aa155874d371e45bb388fe2), [`cc1b66842c`](https://github.com/medusajs/medusa/commit/cc1b66842cbb37c6eab84e2d8b74844c214f38d7), [`24fb102a56`](https://github.com/medusajs/medusa/commit/24fb102a564b1253d1f8b039bb1e435cc5312fbb), [`e85463b2a7`](https://github.com/medusajs/medusa/commit/e85463b2a717751de2e21c39a4c745449b31affe)]:
- @medusajs/types@1.11.14
- @medusajs/utils@1.11.7
- @medusajs/modules-sdk@1.12.9
+3
View File
@@ -0,0 +1,3 @@
# Sales Channel Module
Sales Channel module enables management of sales channels that are used for grouping Products/Carts/Orders etc.
@@ -0,0 +1,40 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { SalesChannel } from "@models"
const salesChannelData = [
{
id: "channel-1",
name: "Channel 1",
description: "Channel description 1",
is_disabled: false,
},
{
id: "channel-2",
name: "Channel 2",
description: "Channel description 2",
is_disabled: false,
},
{
id: "channel-3",
name: "Channel 3",
description: "Channel description 3",
is_disabled: true,
},
]
export async function createSalesChannels(
manager: SqlEntityManager,
channelData: any[] = salesChannelData
): Promise<SalesChannel[]> {
const channels: SalesChannel[] = []
for (let data of channelData) {
const sc = manager.create(SalesChannel, data)
channels.push(sc)
}
await manager.persistAndFlush(channels)
return channels
}
@@ -0,0 +1,243 @@
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { ISalesChannelModuleService } from "@medusajs/types"
import { initialize } from "../../../src"
import { createSalesChannels } from "../../__fixtures__"
import { DB_URL, MikroOrmWrapper } from "../../utils"
jest.setTimeout(30000)
describe("Sales Channel Service", () => {
let service: ISalesChannelModuleService
let testManager: SqlEntityManager
let repositoryManager: SqlEntityManager
beforeEach(async () => {
await MikroOrmWrapper.setupDatabase()
repositoryManager = await MikroOrmWrapper.forkManager()
service = await initialize({
database: {
clientUrl: DB_URL,
schema: process.env.MEDUSA_SALES_CHANNEL_DB_SCHEMA,
},
})
testManager = await MikroOrmWrapper.forkManager()
await createSalesChannels(testManager)
})
afterEach(async () => {
await MikroOrmWrapper.clearDatabase()
})
describe("create", () => {
it("should create a SalesChannel successfully", async () => {
const [created] = await service.create([
{
name: "test",
description: "test",
},
])
const [channel] = await service.list({
name: [created.name],
})
expect(channel.name).toEqual("test")
expect(channel.description).toEqual("test")
})
})
describe("retrieve", () => {
const id = "channel-1"
it("should return SalesChannel for the given id", async () => {
const result = await service.retrieve(id)
expect(result).toEqual(
expect.objectContaining({
id,
})
)
})
it("should throw an error when SalesChannelId with id does not exist", async () => {
let error
try {
await service.retrieve("does-not-exist")
} catch (e) {
error = e
}
expect(error.message).toEqual(
"SalesChannel with id: does-not-exist was not found"
)
})
})
describe("update", () => {
const id = "channel-2"
it("should update the name of the SalesChannel successfully", async () => {
await service.update(id, {
name: "Update name 2",
is_disabled: true,
})
const channel = await service.retrieve(id)
expect(channel.name).toEqual("Update name 2")
expect(channel.is_disabled).toEqual(true)
})
it("should throw an error when a id does not exist", async () => {
let error
try {
await service.update("does-not-exist", {
name: "does-not-exist",
})
} catch (e) {
error = e
}
expect(error.message).toEqual(
'SalesChannel with id "does-not-exist" not found'
)
})
})
describe("list", () => {
it("should return a list of SalesChannels", async () => {
const result = await service.list()
expect(result).toEqual([
expect.objectContaining({
id: "channel-1",
}),
expect.objectContaining({
id: "channel-2",
}),
expect.objectContaining({
id: "channel-3",
}),
])
})
it("should list SalesChannels by name", async () => {
const result = await service.list({
name: ["Channel 2", "Channel 3"],
})
expect(result).toEqual([
expect.objectContaining({
id: "channel-2",
}),
expect.objectContaining({
id: "channel-3",
}),
])
})
})
describe("listAndCount", () => {
it("should return sales channels and count", async () => {
const [result, count] = await service.listAndCount()
expect(count).toEqual(3)
expect(result).toEqual([
expect.objectContaining({
id: "channel-1",
}),
expect.objectContaining({
id: "channel-2",
}),
expect.objectContaining({
id: "channel-3",
}),
])
})
it("should return sales channels and count when filtered", async () => {
const [result, count] = await service.listAndCount({
id: ["channel-2"],
})
expect(count).toEqual(1)
expect(result).toEqual([
expect.objectContaining({
id: "channel-2",
}),
])
})
it("should return sales channels and count when using skip and take", async () => {
const [results, count] = await service.listAndCount(
{},
{ skip: 1, take: 1 }
)
expect(count).toEqual(3)
expect(results).toEqual([
expect.objectContaining({
id: "channel-2",
}),
])
})
it("should return requested fields", async () => {
const [result, count] = await service.listAndCount(
{},
{
take: 1,
select: ["id", "name"],
}
)
const serialized = JSON.parse(JSON.stringify(result))
expect(count).toEqual(3)
expect(serialized).toEqual([
{
id: "channel-1",
name: "Channel 1",
},
])
})
it("should filter disabled channels", async () => {
const [result, count] = await service.listAndCount(
{ is_disabled: true },
{ select: ["id"] }
)
const serialized = JSON.parse(JSON.stringify(result))
expect(count).toEqual(1)
expect(serialized).toEqual([
{
id: "channel-3",
},
])
})
})
describe("delete", () => {
const id = "channel-2"
it("should delete the SalesChannel given an id successfully", async () => {
await service.delete([id])
const result = await service.list({
id: [id],
})
expect(result).toHaveLength(0)
})
})
})
@@ -0,0 +1,6 @@
if (typeof process.env.DB_TEMP_NAME === "undefined") {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
process.env.DB_TEMP_NAME = `medusa-sales-channel-integration-${tempName}`
}
process.env.MEDUSA_SALES_CHANNEL_DB_SCHEMA = "public"
@@ -0,0 +1,3 @@
import { JestUtils } from "medusa-test-utils"
JestUtils.afterAllHookDropDatabase()
@@ -0,0 +1,6 @@
import { ModuleServiceInitializeOptions } from "@medusajs/types"
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
schema: "public",
clientUrl: "medusa-sales-channel-test",
}
@@ -0,0 +1,18 @@
import {TestDatabaseUtils} from "medusa-test-utils"
import * as SalesChannelModels from "@models"
const pathToMigrations = "../../src/migrations"
const mikroOrmEntities = SalesChannelModels as unknown as any[]
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper({
mikroOrmEntities,
pathToMigrations,
})
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig({
mikroOrmEntities,
pathToMigrations,
})
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
@@ -0,0 +1 @@
export * from "./database"
@@ -0,0 +1,22 @@
module.exports = {
moduleNameMapper: {
"^@models": "<rootDir>/src/models",
"^@services": "<rootDir>/src/services",
"^@repositories": "<rootDir>/src/repositories",
"^@types": "<rootDir>/src/types",
},
transform: {
"^.+\\.[jt]s?$": [
"ts-jest",
{
tsconfig: "tsconfig.spec.json",
isolatedModules: true,
},
],
},
testEnvironment: `node`,
moduleFileExtensions: [`js`, `ts`],
modulePathIgnorePatterns: ["dist/"],
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
}
@@ -0,0 +1,8 @@
import * as entities from "./src/models"
module.exports = {
entities: Object.values(entities),
schema: "public",
clientUrl: "postgres://postgres@localhost/medusa-sales-channel",
type: "postgresql",
}
@@ -0,0 +1,61 @@
{
"name": "@medusajs/sales-channel",
"version": "0.1.1",
"description": "Medusa Sales Channel module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"engines": {
"node": ">=16"
},
"bin": {
"medusa-sales-channel-seed": "dist/scripts/bin/run-seed.js"
},
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa",
"directory": "packages/sales-channel"
},
"publishConfig": {
"access": "public"
},
"author": "Medusa",
"license": "MIT",
"scripts": {
"watch": "tsc --build --watch",
"watch:test": "tsc --build tsconfig.spec.json --watch",
"prepublishOnly": "cross-env NODE_ENV=production tsc --build && tsc-alias -p tsconfig.json",
"build": "rimraf dist && tsc --build && tsc-alias -p tsconfig.json",
"test": "jest --runInBand --bail --forceExit -- src/**/__tests__/**/*.ts",
"test:integration": "jest --forceExit -- integration-tests/**/__tests__/**/*.ts",
"migration:generate": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:generate",
"migration:initial": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create --initial",
"migration:create": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create",
"migration:up": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:up",
"orm:cache:clear": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm cache:clear"
},
"devDependencies": {
"@mikro-orm/cli": "5.9.7",
"cross-env": "^5.2.1",
"jest": "^29.6.3",
"medusa-test-utils": "^1.1.42",
"rimraf": "^3.0.2",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.1",
"tsc-alias": "^1.8.6",
"typescript": "^5.1.6"
},
"dependencies": {
"@medusajs/modules-sdk": "^1.12.9",
"@medusajs/types": "^1.11.14",
"@medusajs/utils": "^1.11.7",
"@mikro-orm/core": "5.9.7",
"@mikro-orm/migrations": "5.9.7",
"@mikro-orm/postgresql": "5.9.7",
"awilix": "^8.0.0",
"dotenv": "^16.4.5",
"knex": "2.4.2"
}
}
@@ -0,0 +1,27 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModulesSdkUtils } from "@medusajs/utils"
import * as SalesChannelModels from "@models"
import { moduleDefinition } from "./module-definition"
export default moduleDefinition
const migrationScriptOptions = {
moduleName: Modules.SALES_CHANNEL,
models: SalesChannelModels,
pathToMigrations: __dirname + "/migrations",
}
export const runMigrations = ModulesSdkUtils.buildMigrationScript(
migrationScriptOptions
)
export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
migrationScriptOptions
)
export * from "./initialize"
export * from "./types"
export * from "./loaders"
export * from "./models"
export * from "./services"
@@ -0,0 +1,34 @@
import {
ExternalModuleDeclaration,
InternalModuleDeclaration,
MedusaModule,
MODULE_PACKAGE_NAMES,
Modules,
} from "@medusajs/modules-sdk"
import { ModulesSdkTypes, ISalesChannelModuleService } from "@medusajs/types"
import { InitializeModuleInjectableDependencies } from "@types"
import { moduleDefinition } from "../module-definition"
export const initialize = async (
options?:
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
| ExternalModuleDeclaration
| InternalModuleDeclaration,
injectedDependencies?: InitializeModuleInjectableDependencies
): Promise<ISalesChannelModuleService> => {
const serviceKey = Modules.SALES_CHANNEL
const loaded = await MedusaModule.bootstrap<ISalesChannelModuleService>({
moduleKey: serviceKey,
defaultPath: MODULE_PACKAGE_NAMES[Modules.SALES_CHANNEL],
declaration: options as
| InternalModuleDeclaration
| ExternalModuleDeclaration,
injectedDependencies,
moduleExports: moduleDefinition,
})
return loaded[serviceKey]
}
@@ -0,0 +1,31 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import { SalesChannel } from "@models"
export const LinkableKeys = {
sales_channel_id: SalesChannel.name,
}
const entityLinkableKeysMap: MapToConfig = {}
Object.entries(LinkableKeys).forEach(([key, value]) => {
entityLinkableKeysMap[value] ??= []
entityLinkableKeysMap[value].push({
mapTo: key,
valueFrom: key.split("_").pop()!,
})
})
export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap
export const joinerConfig: ModuleJoinerConfig = {
serviceName: Modules.SALES_CHANNEL,
primaryKeys: ["id"],
linkableKeys: LinkableKeys,
alias: [
{
name: ["sales_channel", "sales_channels"],
args: { entity: "SalesChannel" },
},
],
} as ModuleJoinerConfig
@@ -0,0 +1,37 @@
import {
InternalModuleDeclaration,
LoaderOptions,
Modules,
} from "@medusajs/modules-sdk"
import { ModulesSdkTypes } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema } from "@mikro-orm/core"
import * as SalesChannelModels from "@models"
export default async (
{
options,
container,
logger,
}: LoaderOptions<
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
>,
moduleDeclaration?: InternalModuleDeclaration
): Promise<void> => {
const entities = Object.values(
SalesChannelModels
) as unknown as EntitySchema[]
const pathToMigrations = __dirname + "/../migrations"
await ModulesSdkUtils.mikroOrmConnectionLoader({
moduleName: Modules.SALES_CHANNEL,
entities,
container,
options,
moduleDeclaration,
logger,
pathToMigrations,
})
}
@@ -0,0 +1,10 @@
import { ModulesSdkUtils } from "@medusajs/utils"
import * as ModuleModels from "@models"
import * as ModuleRepositories from "@repositories"
import * as ModuleServices from "@services"
export default ModulesSdkUtils.moduleContainerLoaderFactory({
moduleModels: ModuleModels,
moduleRepositories: ModuleRepositories,
moduleServices: ModuleServices,
})
@@ -0,0 +1,2 @@
export * from "./connection"
export * from "./container"
@@ -0,0 +1,114 @@
{
"namespaces": [
"public"
],
"name": "public",
"tables": [
{
"columns": {
"id": {
"name": "id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"name": {
"name": "name",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"description": {
"name": "description",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"is_disabled": {
"name": "is_disabled",
"type": "boolean",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"default": "false",
"mappedType": "boolean"
},
"metadata": {
"name": "metadata",
"type": "jsonb",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "json"
},
"created_at": {
"name": "created_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"length": 6,
"default": "now()",
"mappedType": "datetime"
},
"updated_at": {
"name": "updated_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"length": 6,
"default": "now()",
"mappedType": "datetime"
},
"deleted_at": {
"name": "deleted_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"length": 6,
"mappedType": "datetime"
}
},
"name": "sales_channel",
"schema": "public",
"indexes": [
{
"columnNames": [
"deleted_at"
],
"composite": false,
"keyName": "IDX_sales_channel_deleted_at",
"primary": false,
"unique": false
},
{
"keyName": "sales_channel_pkey",
"columnNames": [
"id"
],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {}
}
]
}
@@ -0,0 +1,12 @@
import { Migration } from "@mikro-orm/migrations"
export class Migration20240115152146 extends Migration {
async up(): Promise<void> {
this.addSql(
'create table if not exists "sales_channel" ("id" text not null, "name" text not null, "description" text null, "is_disabled" boolean not null default false, "metadata" jsonb NULL, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "sales_channel_pkey" primary key ("id"));'
)
this.addSql(
'create index "IDX_sales_channel_deleted_at" on "sales_channel" ("deleted_at");'
)
}
}
@@ -0,0 +1 @@
export { default as SalesChannel } from "./sales-channel"
@@ -0,0 +1,67 @@
import { DALUtils, Searchable, generateEntityId } from "@medusajs/utils"
import { DAL } from "@medusajs/types"
import {
BeforeCreate,
Entity,
Filter,
Index,
OnInit,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
type SalesChannelOptionalProps = "is_disabled" | DAL.EntityDateColumns
@Entity()
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class SalesChannel {
[OptionalProps]?: SalesChannelOptionalProps
@PrimaryKey({ columnType: "text" })
id!: string
@Searchable()
@Property({ columnType: "text" })
name!: string
@Searchable()
@Property({ columnType: "text", nullable: true })
description: string | null = null
@Property({ columnType: "boolean", default: false })
is_disabled = false
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
created_at: Date
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
@Index({ name: "IDX_sales_channel_deleted_at" })
@Property({ columnType: "timestamptz", nullable: true })
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "sc")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "sc")
}
}
@@ -0,0 +1,13 @@
import { ModuleExports } from "@medusajs/types"
import { SalesChannelModuleService } from "@services"
import loadConnection from "./loaders/connection"
import loadContainer from "./loaders/container"
const service = SalesChannelModuleService
const loaders = [loadContainer, loadConnection] as any
export const moduleDefinition: ModuleExports = {
service,
loaders,
}
@@ -0,0 +1 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
@@ -0,0 +1,31 @@
#!/usr/bin/env node
import { ModulesSdkUtils } from "@medusajs/utils"
import { Modules } from "@medusajs/modules-sdk"
import * as ProductModels from "@models"
import { createSalesChannels } from "../seed-utils"
import { EOL } from "os"
const args = process.argv
const path = args.pop() as string
export default (async () => {
const { config } = await import("dotenv")
config()
if (!path) {
throw new Error(
`filePath is required.${EOL}Example: medusa-product-seed <filePath>`
)
}
const run = ModulesSdkUtils.buildSeedScript({
moduleName: Modules.PRODUCT,
models: ProductModels,
pathToMigrations: __dirname + "/../../migrations",
seedHandler: async ({ manager, data }) => {
const { salesChannelData } = data
await createSalesChannels(manager, salesChannelData)
},
})
await run({ path })
})()
@@ -0,0 +1,16 @@
import { SalesChannel } from "@models"
import { RequiredEntityData } from "@mikro-orm/core"
import { SqlEntityManager } from "@mikro-orm/postgresql"
export async function createSalesChannels(
manager: SqlEntityManager,
data: RequiredEntityData<SalesChannel>[]
) {
const channels = data.map((channel) => {
return manager.create(SalesChannel, channel)
})
await manager.persistAndFlush(channels)
return channels
}
@@ -0,0 +1,11 @@
import { asValue } from "awilix"
export const salesChannelRepositoryMock = {
salesChannelRepository: asValue({
find: jest.fn().mockImplementation(async ({ where: { code } }) => {
return [{}]
}),
findAndCount: jest.fn().mockResolvedValue([[], 0]),
getFreshManager: jest.fn().mockResolvedValue({}),
}),
}
@@ -0,0 +1,47 @@
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../loaders/container"
import { salesChannelRepositoryMock } from "../__fixtures__/sales-channel"
describe("Sales channel service", function () {
let container
beforeEach(async function () {
jest.clearAllMocks()
container = createMedusaContainer()
container.register("manager", asValue({}))
await ContainerLoader({ container })
container.register(salesChannelRepositoryMock)
})
it("should list sales channels with filters and relations", async function () {
const salesChannelRepository = container.resolve("salesChannelRepository")
const salesChannelService = container.resolve("salesChannelService")
const config = {
select: ["id", "name"],
}
await salesChannelService.list({}, config)
expect(salesChannelRepository.find).toHaveBeenCalledWith(
{
where: {},
options: {
fields: ["id", "name"],
limit: 15,
offset: 0,
orderBy: {
id: "ASC",
},
withDeleted: undefined,
populate: [],
},
},
expect.any(Object)
)
})
})
@@ -0,0 +1 @@
export { default as SalesChannelModuleService } from "./sales-channel-module"
@@ -0,0 +1,175 @@
import {
Context,
CreateSalesChannelDTO,
DAL,
FilterableSalesChannelProps,
InternalModuleDeclaration,
ISalesChannelModuleService,
ModuleJoinerConfig,
ModulesSdkTypes,
SalesChannelDTO,
UpdateSalesChannelDTO,
} from "@medusajs/types"
import {
InjectManager,
InjectTransactionManager,
isString,
MedusaContext,
ModulesSdkUtils,
promiseAll,
} from "@medusajs/utils"
import { SalesChannel } from "@models"
import { UpsertSalesChannelDTO } from "@medusajs/types"
import { UpdateSalesChanneInput } from "@types"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
salesChannelService: ModulesSdkTypes.InternalModuleService<any>
}
export default class SalesChannelModuleService<
TEntity extends SalesChannel = SalesChannel
>
extends ModulesSdkUtils.abstractModuleServiceFactory<
InjectedDependencies,
SalesChannelDTO,
{}
>(SalesChannel, [], entityNameToLinkableKeysMap)
implements ISalesChannelModuleService
{
protected baseRepository_: DAL.RepositoryService
protected readonly salesChannelService_: ModulesSdkTypes.InternalModuleService<TEntity>
constructor(
{ baseRepository, salesChannelService }: InjectedDependencies,
protected readonly moduleDeclaration: InternalModuleDeclaration
) {
// @ts-ignore
super(...arguments)
this.baseRepository_ = baseRepository
this.salesChannelService_ = salesChannelService
}
__joinerConfig(): ModuleJoinerConfig {
return joinerConfig
}
async create(
data: CreateSalesChannelDTO[],
sharedContext?: Context
): Promise<SalesChannelDTO[]>
async create(
data: CreateSalesChannelDTO,
sharedContext?: Context
): Promise<SalesChannelDTO>
@InjectManager("baseRepository_")
async create(
data: CreateSalesChannelDTO | CreateSalesChannelDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<SalesChannelDTO | SalesChannelDTO[]> {
const input = Array.isArray(data) ? data : [data]
const result = await this.create_(input, sharedContext)
return await this.baseRepository_.serialize<SalesChannelDTO[]>(
Array.isArray(data) ? result : result[0],
{
populate: true,
}
)
}
@InjectTransactionManager("baseRepository_")
async create_(
data: CreateSalesChannelDTO[],
@MedusaContext() sharedContext: Context
): Promise<SalesChannel[]> {
return await this.salesChannelService_.create(data, sharedContext)
}
async update(
id: string,
data: UpdateSalesChannelDTO,
sharedContext?: Context
): Promise<SalesChannelDTO>
async update(
selector: FilterableSalesChannelProps,
data: UpdateSalesChannelDTO,
sharedContext?: Context
): Promise<SalesChannelDTO[]>
@InjectManager("baseRepository_")
async update(
idOrSelector: string | FilterableSalesChannelProps,
data: UpdateSalesChannelDTO | UpdateSalesChannelDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<SalesChannelDTO | SalesChannelDTO[]> {
let normalizedInput: UpdateSalesChanneInput[] = []
if (isString(idOrSelector)) {
normalizedInput = [{ id: idOrSelector, ...data }]
} else {
const channels = await this.salesChannelService_.list(
idOrSelector,
{},
sharedContext
)
normalizedInput = channels.map((channel) => ({
id: channel.id,
...data,
}))
}
const result = await this.update_(normalizedInput, sharedContext)
return await this.baseRepository_.serialize<SalesChannelDTO[]>(
Array.isArray(data) ? result : result[0],
{
populate: true,
}
)
}
@InjectTransactionManager("baseRepository_")
async update_(data: UpdateSalesChannelDTO[], sharedContext: Context) {
return await this.salesChannelService_.update(data, sharedContext)
}
async upsert(
data: UpsertSalesChannelDTO[],
sharedContext?: Context
): Promise<SalesChannelDTO[]>
async upsert(
data: UpsertSalesChannelDTO,
sharedContext?: Context
): Promise<SalesChannelDTO>
@InjectTransactionManager("baseRepository_")
async upsert(
data: UpsertSalesChannelDTO | UpsertSalesChannelDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<SalesChannelDTO | SalesChannelDTO[]> {
const input = Array.isArray(data) ? data : [data]
const forUpdate = input.filter(
(channel): channel is UpdateSalesChannelDTO => !!channel.id
)
const forCreate = input.filter(
(channel): channel is CreateSalesChannelDTO => !channel.id
)
const operations: Promise<SalesChannel[]>[] = []
if (forCreate.length) {
operations.push(this.create_(forCreate, sharedContext))
}
if (forUpdate.length) {
operations.push(this.update_(forUpdate, sharedContext))
}
const result = (await promiseAll(operations)).flat()
return await this.baseRepository_.serialize<
SalesChannelDTO[] | SalesChannelDTO
>(Array.isArray(data) ? result : result[0])
}
}
@@ -0,0 +1,7 @@
import { Logger, UpdateSalesChannelDTO } from "@medusajs/types"
export type InitializeModuleInjectableDependencies = {
logger?: Logger
}
export type UpdateSalesChanneInput = UpdateSalesChannelDTO & { id: string }
@@ -0,0 +1,37 @@
{
"compilerOptions": {
"lib": ["es2020"],
"target": "es2020",
"outDir": "./dist",
"esModuleInterop": true,
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": false,
"noImplicitReturns": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"allowJs": true,
"skipLibCheck": true,
"downlevelIteration": true, // to use ES5 specific tooling
"baseUrl": ".",
"resolveJsonModule": true,
"paths": {
"@models": ["./src/models"],
"@services": ["./src/services"],
"@repositories": ["./src/repositories"],
"@types": ["./src/types"]
}
},
"include": ["src"],
"exclude": [
"dist",
"./src/**/__tests__",
"./src/**/__mocks__",
"./src/**/__fixtures__",
"node_modules"
]
}
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"include": ["src", "integration-tests"],
"exclude": ["node_modules", "dist"],
"compilerOptions": {
"sourceMap": true
}
}