chore(): Reorganize modules (#7210)

**What**
Move all modules to the modules directory
This commit is contained in:
Adrien de Peretti
2024-05-02 17:33:34 +02:00
committed by GitHub
parent 7a351eef09
commit 4eae25e1ef
870 changed files with 91 additions and 62 deletions

View File

@@ -0,0 +1,14 @@
import { Modules, initializeFactory } from "@medusajs/modules-sdk"
import { moduleDefinition } from "./module-definition"
export * from "./models"
export * from "./services"
export const initialize = initializeFactory({
moduleName: Modules.STOCK_LOCATION,
moduleDefinition,
})
export const runMigrations = moduleDefinition.runMigrations
export const revertMigration = moduleDefinition.revertMigration
export default moduleDefinition

View File

@@ -0,0 +1,37 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import { StockLocation } from "./models"
import moduleSchema from "./schema"
export const LinkableKeys = {
stock_location_id: StockLocation.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.STOCK_LOCATION,
primaryKeys: ["id"],
linkableKeys: {
stock_location_id: StockLocation.name,
location_id: StockLocation.name,
},
schema: moduleSchema,
alias: [
{
name: ["stock_location", "stock_locations"],
args: {
entity: "StockLocation",
},
},
],
}

View File

@@ -0,0 +1,270 @@
{
"namespaces": [
"public"
],
"name": "public",
"tables": [
{
"columns": {
"id": {
"name": "id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"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"
},
"address_1": {
"name": "address_1",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"address_2": {
"name": "address_2",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"company": {
"name": "company",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"city": {
"name": "city",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"country_code": {
"name": "country_code",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"phone": {
"name": "phone",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"province": {
"name": "province",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"postal_code": {
"name": "postal_code",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"metadata": {
"name": "metadata",
"type": "jsonb",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "json"
}
},
"name": "stock_location_address",
"schema": "public",
"indexes": [
{
"keyName": "IDX_stock_location_address_deleted_at",
"columnNames": [
"deleted_at"
],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_stock_location_address_deleted_at\" ON \"stock_location_address\" (deleted_at) WHERE deleted_at IS NOT NULL"
},
{
"keyName": "stock_location_address_pkey",
"columnNames": [
"id"
],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {}
},
{
"columns": {
"id": {
"name": "id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"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": {
"name": "name",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"address_id": {
"name": "address_id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"metadata": {
"name": "metadata",
"type": "jsonb",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "json"
}
},
"name": "stock_location",
"schema": "public",
"indexes": [
{
"keyName": "IDX_stock_location_deleted_at",
"columnNames": [
"deleted_at"
],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_stock_location_deleted_at\" ON \"stock_location\" (deleted_at) WHERE deleted_at IS NOT NULL"
},
{
"keyName": "stock_location_pkey",
"columnNames": [
"id"
],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {
"stock_location_address_id_foreign": {
"constraintName": "stock_location_address_id_foreign",
"columnNames": [
"address_id"
],
"localTableName": "public.stock_location",
"referencedColumnNames": [
"id"
],
"referencedTableName": "public.stock_location_address",
"deleteRule": "set null",
"updateRule": "cascade"
}
}
}
]
}

View File

@@ -0,0 +1,23 @@
import { Migration } from '@mikro-orm/migrations';
export class Migration20240307161216 extends Migration {
async up(): Promise<void> {
this.addSql('create table if not exists "stock_location_address" ("id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, "address_1" text not null, "address_2" text null, "company" text null, "city" text null, "country_code" text not null, "phone" text null, "province" text null, "postal_code" text null, "metadata" jsonb null, constraint "stock_location_address_pkey" primary key ("id"));');
this.addSql('CREATE INDEX IF NOT EXISTS "IDX_stock_location_address_deleted_at" ON "stock_location_address" (deleted_at) WHERE deleted_at IS NOT NULL;');
this.addSql('create table if not exists "stock_location" ("id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, "name" text not null, "address_id" text null, "metadata" jsonb null, constraint "stock_location_pkey" primary key ("id"));');
this.addSql('CREATE INDEX IF NOT EXISTS "IDX_stock_location_deleted_at" ON "stock_location" (deleted_at) WHERE deleted_at IS NOT NULL;');
this.addSql('alter table if exists "stock_location" add constraint "stock_location_address_id_foreign" foreign key ("address_id") references "stock_location_address" ("id") on update cascade on delete set null;');
}
async down(): Promise<void> {
this.addSql('alter table if exists "stock_location" drop constraint if exists "stock_location_address_id_foreign";');
this.addSql('drop table if exists "stock_location_address" cascade;');
this.addSql('drop table if exists "stock_location" cascade;');
}
}

View File

@@ -0,0 +1,2 @@
export * from "./stock-location"
export * from "./stock-location-address"

View File

@@ -0,0 +1,79 @@
import {
BeforeCreate,
Entity,
OnInit,
PrimaryKey,
Property,
} from "@mikro-orm/core"
import {
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/utils"
const StockLocationAddressDeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "stock_location_address",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
@Entity()
export class StockLocationAddress {
@PrimaryKey({ columnType: "text" })
id: string
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
created_at: Date
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
@StockLocationAddressDeletedAtIndex.MikroORMIndex()
@Property({ columnType: "timestamptz", nullable: true })
deleted_at: Date | null = null
@Property({ columnType: "text" })
address_1: string
@Property({ columnType: "text", nullable: true })
address_2: string | null
@Property({ columnType: "text", nullable: true })
company: string | null
@Property({ columnType: "text", nullable: true })
city: string | null
@Property({ columnType: "text" })
country_code: string
@Property({ columnType: "text", nullable: true })
phone: string | null
@Property({ columnType: "text", nullable: true })
province: string | null
@Property({ columnType: "text", nullable: true })
postal_code: string | null
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null
@BeforeCreate()
private beforeCreate(): void {
this.id = generateEntityId(this.id, "laddr")
}
@OnInit()
private onInit(): void {
this.id = generateEntityId(this.id, "laddr")
}
}

View File

@@ -0,0 +1,77 @@
import {
BeforeCreate,
Entity,
ManyToOne,
OnInit,
PrimaryKey,
Property,
} from "@mikro-orm/core"
import {
createPsqlIndexStatementHelper,
generateEntityId,
Searchable,
} from "@medusajs/utils"
import { StockLocationAddress } from "./stock-location-address"
const StockLocationDeletedAtIndex = createPsqlIndexStatementHelper({
tableName: "stock_location",
columns: "deleted_at",
where: "deleted_at IS NOT NULL",
})
@Entity()
export class StockLocation {
@PrimaryKey({ columnType: "text" })
id: string
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
created_at: Date
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
@StockLocationDeletedAtIndex.MikroORMIndex()
@Property({ columnType: "timestamptz", nullable: true })
deleted_at: Date | null = null
@Searchable()
@Property({ columnType: "text" })
name: string
@ManyToOne(() => StockLocationAddress, {
fieldName: "address_id",
type: "text",
mapToPk: true,
nullable: true,
onDelete: "cascade",
})
address_id: string | null
@ManyToOne(() => StockLocationAddress, {
nullable: true,
})
address: StockLocationAddress | null
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null
@BeforeCreate()
private beforeCreate(): void {
this.id = generateEntityId(this.id, "sloc")
}
@OnInit()
private onInit(): void {
this.id = generateEntityId(this.id, "sloc")
}
}

View File

@@ -0,0 +1,44 @@
import * as StockLocationModels from "@models"
import * as StockLocationRepostiories from "@repositories"
import * as StockLocationServices from "@services"
import { Modules } from "@medusajs/modules-sdk"
import { ModuleExports } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { StockLocationModuleService } from "@services"
const migrationScriptOptions = {
moduleName: Modules.STOCK_LOCATION,
models: StockLocationModels,
pathToMigrations: __dirname + "/migrations",
}
const runMigrations = ModulesSdkUtils.buildMigrationScript(
migrationScriptOptions
)
const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
migrationScriptOptions
)
const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({
moduleModels: StockLocationModels,
moduleRepositories: StockLocationRepostiories,
moduleServices: StockLocationServices,
})
const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({
moduleName: Modules.STOCK_LOCATION,
moduleModels: Object.values(StockLocationModels),
migrationsPath: __dirname + "/migrations",
})
const service = StockLocationModuleService
const loaders = [containerLoader, connectionLoader]
export const moduleDefinition: ModuleExports = {
service,
loaders,
revertMigration,
runMigrations,
}

View File

@@ -0,0 +1 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"

View File

@@ -0,0 +1,29 @@
export default `
scalar DateTime
scalar JSON
type StockLocation {
id: ID!
created_at: DateTime!
updated_at: DateTime!
deleted_at: DateTime
name: String!
address_id: String
address: StockLocationAddress
metadata: JSON
}
type StockLocationAddress {
id: ID!
created_at: DateTime!
updated_at: DateTime!
deleted_at: DateTime
address_1: String!
address_2: String
company: String
city: String
country_code: String!
phone: String
province: String
postal_code: String
metadata: JSON
}
`

View File

@@ -0,0 +1,5 @@
describe("noop", function () {
it("should run", function () {
expect(true).toBe(true)
})
})

View File

@@ -0,0 +1 @@
export { default as StockLocationModuleService } from "./stock-location-module"

View File

@@ -0,0 +1,263 @@
import { InternalModuleDeclaration } from "@medusajs/modules-sdk"
import {
Context,
CreateStockLocationInput,
IEventBusService,
ModuleJoinerConfig,
StockLocationAddressInput,
StockLocationTypes,
UpdateStockLocationInput,
ModulesSdkTypes,
DAL,
IStockLocationServiceNext,
FilterableStockLocationProps,
} from "@medusajs/types"
import {
InjectManager,
InjectTransactionManager,
MedusaContext,
ModulesSdkUtils,
isString,
} from "@medusajs/utils"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
import { StockLocation, StockLocationAddress } from "../models"
import { UpdateStockLocationNextInput } from "@medusajs/types"
import { UpsertStockLocationInput } from "@medusajs/types"
import { promiseAll } from "@medusajs/utils"
type InjectedDependencies = {
eventBusService: IEventBusService
baseRepository: DAL.RepositoryService
stockLocationService: ModulesSdkTypes.InternalModuleService<any>
stockLocationAddressService: ModulesSdkTypes.InternalModuleService<any>
}
const generateMethodForModels = [StockLocationAddress]
/**
* Service for managing stock locations.
*/
export default class StockLocationModuleService<
TEntity extends StockLocation = StockLocation,
TStockLocationAddress extends StockLocationAddress = StockLocationAddress
>
extends ModulesSdkUtils.abstractModuleServiceFactory<
InjectedDependencies,
StockLocationTypes.StockLocationDTO,
{
StockLocation: { dto: StockLocationTypes.StockLocationDTO }
StockLocationAddress: { dto: StockLocationTypes.StockLocationAddressDTO }
}
>(StockLocation, generateMethodForModels, entityNameToLinkableKeysMap)
implements IStockLocationServiceNext
{
protected readonly eventBusService_: IEventBusService
protected baseRepository_: DAL.RepositoryService
protected readonly stockLocationService_: ModulesSdkTypes.InternalModuleService<TEntity>
protected readonly stockLocationAddressService_: ModulesSdkTypes.InternalModuleService<TStockLocationAddress>
constructor(
{
eventBusService,
baseRepository,
stockLocationService,
stockLocationAddressService,
}: InjectedDependencies,
protected readonly moduleDeclaration?: InternalModuleDeclaration
) {
// @ts-ignore
super(...arguments)
this.baseRepository_ = baseRepository
this.stockLocationService_ = stockLocationService
this.stockLocationAddressService_ = stockLocationAddressService
this.eventBusService_ = eventBusService
}
__joinerConfig(): ModuleJoinerConfig {
return joinerConfig
}
create(
data: CreateStockLocationInput,
context: Context
): Promise<StockLocationTypes.StockLocationDTO>
create(
data: CreateStockLocationInput[],
context: Context
): Promise<StockLocationTypes.StockLocationDTO[]>
/**
* Creates a new stock location.
* @param data - The input data for creating a Stock Location.
* @param context
* @returns The created stock location.
*/
@InjectManager("baseRepository_")
async create(
data: CreateStockLocationInput | CreateStockLocationInput[],
@MedusaContext() context: Context = {}
): Promise<
StockLocationTypes.StockLocationDTO | StockLocationTypes.StockLocationDTO[]
> {
const input = Array.isArray(data) ? data : [data]
const created = await this.create_(input, context)
const serialized = await this.baseRepository_.serialize<
| StockLocationTypes.StockLocationDTO
| StockLocationTypes.StockLocationDTO[]
>(created, { populate: true })
return Array.isArray(data) ? serialized : serialized[0]
}
@InjectTransactionManager("baseRepository_")
async create_(
data: CreateStockLocationInput[],
@MedusaContext() context: Context = {}
): Promise<TEntity[]> {
return await this.stockLocationService_.create(data, context)
}
async upsert(
data: UpsertStockLocationInput,
context?: Context
): Promise<StockLocationTypes.StockLocationDTO>
async upsert(
data: UpsertStockLocationInput[],
context?: Context
): Promise<StockLocationTypes.StockLocationDTO[]>
@InjectManager("baseRepository_")
async upsert(
data: UpsertStockLocationInput | UpsertStockLocationInput[],
@MedusaContext() context: Context = {}
): Promise<
StockLocationTypes.StockLocationDTO | StockLocationTypes.StockLocationDTO[]
> {
const input = Array.isArray(data) ? data : [data]
const result = await this.upsert_(input, context)
return await this.baseRepository_.serialize<
| StockLocationTypes.StockLocationDTO[]
| StockLocationTypes.StockLocationDTO
>(Array.isArray(data) ? result : result[0])
}
@InjectTransactionManager("baseRepository_")
async upsert_(
input: UpsertStockLocationInput[],
@MedusaContext() context: Context = {}
) {
const toUpdate = input.filter(
(location): location is UpdateStockLocationNextInput => !!location.id
) as UpdateStockLocationNextInput[]
const toCreate = input.filter(
(location) => !location.id
) as CreateStockLocationInput[]
const operations: Promise<StockLocation[] | StockLocation>[] = []
if (toCreate.length) {
operations.push(this.create_(toCreate, context))
}
if (toUpdate.length) {
operations.push(this.update_(toUpdate, context))
}
return (await promiseAll(operations)).flat()
}
update(
id: string,
input: UpdateStockLocationNextInput,
context?: Context
): Promise<StockLocationTypes.StockLocationDTO>
update(
selector: FilterableStockLocationProps,
input: UpdateStockLocationNextInput,
context?: Context
): Promise<StockLocationTypes.StockLocationDTO[]>
/**
* Updates an existing stock location.
* @param stockLocationId - The ID of the stock location to update.
* @param updateData - The update data for the stock location.
* @param context
* @returns The updated stock location.
*/
@InjectManager("baseRepository_")
async update(
idOrSelector: string | FilterableStockLocationProps,
data: UpdateStockLocationNextInput | UpdateStockLocationNextInput[],
@MedusaContext() context: Context = {}
): Promise<
StockLocationTypes.StockLocationDTO | StockLocationTypes.StockLocationDTO[]
> {
let normalizedInput:
| (UpdateStockLocationNextInput & { id: string })[]
| { data: any; selector: FilterableStockLocationProps } = []
if (isString(idOrSelector)) {
normalizedInput = [{ id: idOrSelector, ...data }]
} else {
normalizedInput = { data, selector: idOrSelector }
}
const updated = await this.update_(normalizedInput, context)
const serialized = await this.baseRepository_.serialize<
| StockLocationTypes.StockLocationDTO
| StockLocationTypes.StockLocationDTO[]
>(updated, { populate: true })
return Array.isArray(data) ? serialized : serialized[0]
}
@InjectTransactionManager("baseRepository_")
async update_(
data:
| UpdateStockLocationNextInput[]
| UpdateStockLocationNextInput
| { data: any; selector: FilterableStockLocationProps },
@MedusaContext() context: Context = {}
): Promise<TEntity[] | TEntity> {
return await this.stockLocationService_.update(data, context)
}
updateStockLocationAddress(
data: StockLocationAddressInput & { id: string },
context?: Context
): Promise<StockLocationTypes.StockLocationAddressDTO>
updateStockLocationAddress(
data: (StockLocationAddressInput & { id: string })[],
context?: Context
): Promise<StockLocationTypes.StockLocationAddressDTO[]>
@InjectManager("baseRepository_")
async updateStockLocationAddress(
data:
| (StockLocationAddressInput & { id: string })
| (StockLocationAddressInput & { id: string })[],
@MedusaContext() context: Context = {}
) {
const input = Array.isArray(data) ? data : [data]
const updated = await this.updateStockLocationAddress_(input, context)
const serialized = await this.baseRepository_.serialize<
| StockLocationTypes.StockLocationAddressDTO
| StockLocationTypes.StockLocationAddressDTO[]
>(updated, { populate: true })
return Array.isArray(data) ? serialized : serialized[0]
}
@InjectTransactionManager("baseRepository_")
private async updateStockLocationAddress_(
input: (StockLocationAddressInput & { id: string })[],
@MedusaContext() context: Context
) {
return await this.stockLocationAddressService_.update(input, context)
}
}