chore(order): dml (#10292)
* ../../core/types/src/dml/index.ts * ../../core/types/src/dml/index.ts * fix: relationships mapping * handle nullable foreign keys types * handle nullable foreign keys types * handle nullable foreign keys types * continue to update product category repository * fix all product category repositories issues * fix product category service types * fix product module service types * fix product module service types * fix repository template type * refactor: use a singleton DMLToMikroORM factory instance Since the MikroORM MetadataStorage is global, we will also have to turn DML to MikroORM entities conversion use a global bucket as well * refactor: update product module to use DML in tests * wip: tests * WIP product linkable fixes * continue type fixing and start test fixing * test: fix more tests * fix repository * fix pivot table computaion + fix mikro orm repository * fix many to many management and configuration * fix many to many management and configuration * fix many to many management and configuration * update product tag relation configuration * Introduce experimental dml hooks to fix some issues with categories * more fixes * fix product tests * add missing id prefixes * fix product category handle management * test: fix more failing tests * test: make it all green * test: fix breaking tests * fix: build issues * fix: build issues * fix: more breaking tests * refactor: fix issues after merge * refactor: fix issues after merge * refactor: surpress types error * test: fix DML failing tests * improve many to many inference + tests * Wip fix columns from product entity * remove product model before create hook and manage handle validation and transformation at the service level * test: fix breaking unit tests * fix: product module service to not update handle on product update * fix define link and joiner config * test: fix joiner config test * test: fix joiner config test * fix joiner config primary keys * Fix joiner config builder * Fix joiner config builder * test: remove only modifier from test * refactor: remove hooks usage from product collection * refactor: remove hooks usage from product-option * refactor: remove hooks usage for computing category handle * refactor: remove hooks usage from productCategory model * refactor: remove hooks from DML * refactor: remove cruft * order dml * cleanup * re add foerign key indexes * wip * chore: remove unused types * wip * changes * rm raw * autoincrement * wip * rel * refactor: cleanup * migration and models configuration adjustments * cleanup * number searchable * fix random ordering * fix * test: fix product-category tests * test: update breaking DML tests * test: array assertion to not care about ordering * fix: temporarily apply id ordering for products * types * wip * WIP type improvements * update order models * partially fix types temporarely * rel * fix: recursive type issue * improve type inference breaks * improve type inference breaks * update models * rm nullable * default value * repository * update default value handling * fix unit tests * WIP * toMikroORM * fix relations * cascades * fix * experimental dml hooks * rm migration * serial * nullable autoincrement * fix model * model changes * fix one to one DML * order test * fix addresses * fix unit tests * Re align dml entity name inference * update model table name config * update model table name config * revert * update return relation * WIP * hasOne * models * fix * model * initial commit * cart service * order module * utils unit test * index engine * changeset * merge * fix hasOne with fk * update * free text filter per entity * tests * prod category * property string many to many * fix big number * link modules migration set names * merge * shipping option rules * serializer * unit test * fix test mikro orm init * fix test mikro orm init * Maintain merge object properties * fix test mikro orm init * prevent unit test from connecting to db * wip * fix test * fix test * link test * schema * models * auto increment * hook * model hooks * order * wip * orm version * request return field * fix return configuration on order model * workflows * core flows * unit test * test * base repo * test * base repo * test fix * inventory move * locking inventory * test * free text fix * rm timeout mock * migrate fulfillment values * v6.4.3 * cleanup * link-modules update sql * revert test * remove fake timers --------- Co-authored-by: adrien2p <adrien.deperetti@gmail.com> Co-authored-by: Harminder Virk <virk.officials@gmail.com> Co-authored-by: Oli Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
co-authored by
adrien2p
Harminder Virk
Oli Juhl
parent
05c8a67d8e
commit
cc73802ab3
@@ -63,7 +63,7 @@ class ProductOptionValue {
|
||||
fieldName: "option_id",
|
||||
mapToPk: true,
|
||||
nullable: true,
|
||||
onDelete: "cascade",
|
||||
deleteRule: "cascade",
|
||||
})
|
||||
option_id: string | null
|
||||
|
||||
@@ -88,7 +88,7 @@ class ProductVariant {
|
||||
@ManyToOne(() => Product, {
|
||||
columnType: "text",
|
||||
nullable: true,
|
||||
onDelete: "cascade",
|
||||
deleteRule: "cascade",
|
||||
fieldName: "product_id",
|
||||
mapToPk: true,
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Entity, MikroORM, OnInit, Property } from "@mikro-orm/core"
|
||||
import { defineConfig } from "@mikro-orm/postgresql"
|
||||
import { BaseEntity } from "../base-entity"
|
||||
|
||||
describe("BaseEntity", () => {
|
||||
@@ -10,11 +11,15 @@ describe("BaseEntity", () => {
|
||||
}
|
||||
}
|
||||
|
||||
const orm = await MikroORM.init({
|
||||
entities: [Entity1],
|
||||
dbName: "test",
|
||||
type: "postgresql",
|
||||
})
|
||||
const orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [Entity1],
|
||||
dbName: "test",
|
||||
user: "postgres",
|
||||
password: "",
|
||||
connect: false,
|
||||
})
|
||||
)
|
||||
|
||||
const manager = orm.em.fork()
|
||||
const entity1 = manager.create(Entity1, {})
|
||||
@@ -28,11 +33,15 @@ describe("BaseEntity", () => {
|
||||
@Entity()
|
||||
class Entity1 extends BaseEntity {}
|
||||
|
||||
const orm = await MikroORM.init({
|
||||
entities: [Entity1],
|
||||
dbName: "test",
|
||||
type: "postgresql",
|
||||
})
|
||||
const orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [Entity1],
|
||||
dbName: "test",
|
||||
user: "postgres",
|
||||
password: "",
|
||||
connect: false,
|
||||
})
|
||||
)
|
||||
|
||||
const manager = orm.em.fork()
|
||||
const entity1 = manager.create(Entity1, {})
|
||||
@@ -52,11 +61,15 @@ describe("BaseEntity", () => {
|
||||
@Entity()
|
||||
class ProductOptionValue extends BaseEntity {}
|
||||
|
||||
const orm = await MikroORM.init({
|
||||
entities: [ProductModel, ProductCategoryEntity, ProductOptionValue],
|
||||
dbName: "test",
|
||||
type: "postgresql",
|
||||
})
|
||||
const orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [ProductModel, ProductCategoryEntity, ProductOptionValue],
|
||||
dbName: "test",
|
||||
user: "postgres",
|
||||
password: "",
|
||||
connect: false,
|
||||
})
|
||||
)
|
||||
|
||||
const manager = orm.em.fork()
|
||||
|
||||
@@ -105,11 +118,15 @@ describe("BaseEntity", () => {
|
||||
}
|
||||
}
|
||||
|
||||
const orm = await MikroORM.init({
|
||||
entities: [ProductModel, ProductCategoryEntity, ProductOptionValue],
|
||||
dbName: "test",
|
||||
type: "postgresql",
|
||||
})
|
||||
const orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [ProductModel, ProductCategoryEntity, ProductOptionValue],
|
||||
dbName: "test",
|
||||
user: "postgres",
|
||||
password: "",
|
||||
connect: false,
|
||||
})
|
||||
)
|
||||
|
||||
const manager = orm.em.fork()
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BigNumberRawValue } from "@medusajs/types"
|
||||
import { Entity, MikroORM, PrimaryKey } from "@mikro-orm/core"
|
||||
import { defineConfig } from "@mikro-orm/postgresql"
|
||||
import { BigNumber } from "../../../totals/big-number"
|
||||
import { MikroOrmBigNumberProperty } from "../big-number-field"
|
||||
|
||||
@@ -23,11 +24,15 @@ describe("@MikroOrmBigNumberProperty", () => {
|
||||
let orm!: MikroORM
|
||||
|
||||
beforeEach(async () => {
|
||||
orm = await MikroORM.init({
|
||||
entities: [TestAmount],
|
||||
dbName: "test",
|
||||
type: "postgresql",
|
||||
})
|
||||
orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [TestAmount],
|
||||
dbName: "test",
|
||||
user: "postgres",
|
||||
password: "",
|
||||
connect: false,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -51,9 +56,7 @@ describe("@MikroOrmBigNumberProperty", () => {
|
||||
try {
|
||||
;(testAmount as any).amount = null
|
||||
} catch (e) {
|
||||
expect(e.message).toEqual(
|
||||
"Invalid BigNumber value: null. Should be one of: string, number, BigNumber (bignumber.js), BigNumberRawValue"
|
||||
)
|
||||
expect(e.message).toEqual("Cannot set value null for amount.")
|
||||
}
|
||||
|
||||
testAmount.nullable_amount = null
|
||||
|
||||
+14
-9
@@ -1,4 +1,5 @@
|
||||
import { MikroORM } from "@mikro-orm/core"
|
||||
import { defineConfig } from "@mikro-orm/postgresql"
|
||||
import { SearchableEntity1, SearchableEntity2 } from "../__fixtures__/utils"
|
||||
import { mikroOrmFreeTextSearchFilterOptionsFactory } from "../mikro-orm-free-text-search-filter"
|
||||
|
||||
@@ -6,21 +7,23 @@ describe("mikroOrmFreeTextSearchFilterOptionsFactory", () => {
|
||||
let orm
|
||||
|
||||
beforeEach(async () => {
|
||||
orm = await MikroORM.init({
|
||||
entities: [SearchableEntity1, SearchableEntity2],
|
||||
dbName: "test",
|
||||
type: "postgresql",
|
||||
})
|
||||
orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [SearchableEntity1, SearchableEntity2],
|
||||
user: "postgres",
|
||||
password: "",
|
||||
dbName: "test",
|
||||
connect: false,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it("should return a filter function that filters entities based on the free text search value", async () => {
|
||||
const entityManager = orm.em.fork()
|
||||
const freeTextSearchValue = "search"
|
||||
|
||||
const models = [SearchableEntity1, SearchableEntity2]
|
||||
|
||||
let filterConstraints = mikroOrmFreeTextSearchFilterOptionsFactory(
|
||||
models
|
||||
SearchableEntity1.name
|
||||
).cond(
|
||||
{
|
||||
value: freeTextSearchValue,
|
||||
@@ -51,7 +54,9 @@ describe("mikroOrmFreeTextSearchFilterOptionsFactory", () => {
|
||||
],
|
||||
})
|
||||
|
||||
filterConstraints = mikroOrmFreeTextSearchFilterOptionsFactory(models).cond(
|
||||
filterConstraints = mikroOrmFreeTextSearchFilterOptionsFactory(
|
||||
SearchableEntity2.name
|
||||
).cond(
|
||||
{
|
||||
value: freeTextSearchValue,
|
||||
fromEntity: SearchableEntity2.name,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { MikroORM } from "@mikro-orm/core"
|
||||
import { defineConfig } from "@mikro-orm/postgresql"
|
||||
import {
|
||||
Entity1WithUnDecoratedProp,
|
||||
Entity2WithUnDecoratedProp,
|
||||
@@ -11,18 +12,22 @@ import { mikroOrmSerializer } from "../mikro-orm-serializer"
|
||||
|
||||
describe("mikroOrmSerializer", () => {
|
||||
beforeEach(async () => {
|
||||
await MikroORM.init({
|
||||
entities: [
|
||||
Entity1WithUnDecoratedProp,
|
||||
Entity2WithUnDecoratedProp,
|
||||
Product,
|
||||
ProductOption,
|
||||
ProductOptionValue,
|
||||
ProductVariant,
|
||||
],
|
||||
dbName: "test",
|
||||
type: "postgresql",
|
||||
})
|
||||
await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [
|
||||
Entity1WithUnDecoratedProp,
|
||||
Entity2WithUnDecoratedProp,
|
||||
Product,
|
||||
ProductOption,
|
||||
ProductOptionValue,
|
||||
ProductVariant,
|
||||
],
|
||||
user: "postgres",
|
||||
password: "",
|
||||
dbName: "test",
|
||||
connect: false,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it("should serialize an entity", async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { CustomTsMigrationGenerator } from "../mikro-orm-create-connection"
|
||||
|
||||
function unwrapSql(sql: string) {
|
||||
return sql.match(/this.addSql\('(.*?)'\)/)?.[1]
|
||||
return sql.toString().match(/this.addSql\(`(.*?)`\)/)?.[1]
|
||||
}
|
||||
|
||||
describe("CustomTsMigrationGenerator", () => {
|
||||
|
||||
@@ -26,20 +26,24 @@ export function MikroOrmBigNumberProperty(
|
||||
set(value: BigNumberInput) {
|
||||
if (options?.nullable && !isPresent(value)) {
|
||||
this.__helper.__data[columnName] = null
|
||||
this.__helper.__data[rawColumnName]
|
||||
this.__helper.__data[rawColumnName] = null
|
||||
this[rawColumnName] = null
|
||||
} else {
|
||||
let bigNumber: BigNumber
|
||||
|
||||
if (value instanceof BigNumber) {
|
||||
bigNumber = value
|
||||
} else if (this[rawColumnName]) {
|
||||
const precision = this[rawColumnName].precision
|
||||
bigNumber = new BigNumber(value, {
|
||||
precision,
|
||||
})
|
||||
} else {
|
||||
bigNumber = new BigNumber(value)
|
||||
try {
|
||||
if (value instanceof BigNumber) {
|
||||
bigNumber = value
|
||||
} else if (this[rawColumnName]) {
|
||||
const precision = this[rawColumnName].precision
|
||||
bigNumber = new BigNumber(value, {
|
||||
precision,
|
||||
})
|
||||
} else {
|
||||
bigNumber = new BigNumber(value)
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(`Cannot set value ${value} for ${columnName}.`)
|
||||
}
|
||||
|
||||
const raw = bigNumber.raw!
|
||||
@@ -80,6 +84,7 @@ export function MikroOrmBigNumberProperty(
|
||||
type: "any",
|
||||
columnType: "numeric",
|
||||
trackChanges: false,
|
||||
runtimeType: "any",
|
||||
...options,
|
||||
})(target, columnName)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const DB_HOST = process.env.DB_HOST ?? "localhost"
|
||||
const DB_USERNAME = process.env.DB_USERNAME ?? ""
|
||||
const DB_USERNAME = process.env.DB_USERNAME ?? "postgres"
|
||||
const DB_PASSWORD = process.env.DB_PASSWORD
|
||||
|
||||
export const pgGodCredentials = {
|
||||
|
||||
+11
-9
@@ -1,3 +1,4 @@
|
||||
import { BigNumberRawValue } from "@medusajs/types"
|
||||
import {
|
||||
BeforeCreate,
|
||||
Collection,
|
||||
@@ -13,11 +14,11 @@ import {
|
||||
Unique,
|
||||
wrap,
|
||||
} from "@mikro-orm/core"
|
||||
import { mikroOrmBaseRepositoryFactory } from "../../mikro-orm-repository"
|
||||
import { defineConfig } from "@mikro-orm/postgresql"
|
||||
import BigNumber from "bignumber.js"
|
||||
import { dropDatabase } from "pg-god"
|
||||
import { MikroOrmBigNumberProperty } from "../../big-number-field"
|
||||
import BigNumber from "bignumber.js"
|
||||
import { BigNumberRawValue } from "@medusajs/types"
|
||||
import { mikroOrmBaseRepositoryFactory } from "../../mikro-orm-repository"
|
||||
import { getDatabaseURL, pgGodCredentials } from "../__fixtures__/database"
|
||||
|
||||
const dbName = "mikroorm-integration-1"
|
||||
@@ -78,7 +79,7 @@ class Entity2 {
|
||||
nullable: true,
|
||||
mapToPk: true,
|
||||
fieldName: "entity1_id",
|
||||
onDelete: "set null",
|
||||
deleteRule: "set null",
|
||||
})
|
||||
entity1_id: string
|
||||
|
||||
@@ -143,11 +144,12 @@ describe("mikroOrmRepository", () => {
|
||||
pgGodCredentials
|
||||
)
|
||||
|
||||
orm = await MikroORM.init({
|
||||
entities: [Entity1, Entity2],
|
||||
clientUrl: getDatabaseURL(dbName),
|
||||
type: "postgresql",
|
||||
})
|
||||
orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [Entity1, Entity2],
|
||||
clientUrl: getDatabaseURL(dbName),
|
||||
})
|
||||
)
|
||||
|
||||
const generator = orm.getSchemaGenerator()
|
||||
await generator.ensureDatabase()
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { mikroOrmUpdateDeletedAtRecursively } from "../../utils"
|
||||
import { MikroORM } from "@mikro-orm/core"
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import { defineConfig, SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import { dropDatabase } from "pg-god"
|
||||
import { mikroOrmUpdateDeletedAtRecursively } from "../../utils"
|
||||
import { getDatabaseURL, pgGodCredentials } from "../__fixtures__/database"
|
||||
import {
|
||||
DeepRecursiveEntity1,
|
||||
DeepRecursiveEntity2,
|
||||
@@ -12,8 +14,6 @@ import {
|
||||
RecursiveEntity1,
|
||||
RecursiveEntity2,
|
||||
} from "../__fixtures__/utils"
|
||||
import { dropDatabase } from "pg-god"
|
||||
import { getDatabaseURL, pgGodCredentials } from "../__fixtures__/database"
|
||||
|
||||
const dbName = "mikroorm-utils-integration-1"
|
||||
|
||||
@@ -38,21 +38,22 @@ describe("mikroOrmUpdateDeletedAtRecursively", () => {
|
||||
pgGodCredentials
|
||||
)
|
||||
|
||||
orm = await MikroORM.init({
|
||||
entities: [
|
||||
Entity1,
|
||||
Entity2,
|
||||
RecursiveEntity1,
|
||||
RecursiveEntity2,
|
||||
DeepRecursiveEntity1,
|
||||
DeepRecursiveEntity2,
|
||||
DeepRecursiveEntity3,
|
||||
DeepRecursiveEntity4,
|
||||
InternalCircularDependencyEntity1,
|
||||
],
|
||||
clientUrl: getDatabaseURL(dbName),
|
||||
type: "postgresql",
|
||||
})
|
||||
orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [
|
||||
Entity1,
|
||||
Entity2,
|
||||
RecursiveEntity1,
|
||||
RecursiveEntity2,
|
||||
DeepRecursiveEntity1,
|
||||
DeepRecursiveEntity2,
|
||||
DeepRecursiveEntity3,
|
||||
DeepRecursiveEntity4,
|
||||
InternalCircularDependencyEntity1,
|
||||
],
|
||||
clientUrl: getDatabaseURL(dbName),
|
||||
})
|
||||
)
|
||||
|
||||
const generator = orm.getSchemaGenerator()
|
||||
await generator.ensureDatabase()
|
||||
|
||||
@@ -45,34 +45,38 @@ export async function mikroOrmCreateConnection(
|
||||
schema = database.connection.context?.client?.config?.searchPath
|
||||
}
|
||||
|
||||
const { MikroORM } = await import("@mikro-orm/postgresql")
|
||||
return await MikroORM.init({
|
||||
discovery: { disableDynamicFileAccess: true, warnWhenNoEntities: false },
|
||||
entities,
|
||||
debug: database.debug ?? process.env.NODE_ENV?.startsWith("dev") ?? false,
|
||||
baseDir: process.cwd(),
|
||||
clientUrl,
|
||||
schema,
|
||||
driverOptions,
|
||||
tsNode: process.env.APP_ENV === "development",
|
||||
type: "postgresql",
|
||||
filters: database.filters ?? {},
|
||||
migrations: {
|
||||
disableForeignKeys: false,
|
||||
path: pathToMigrations,
|
||||
generator: CustomTsMigrationGenerator,
|
||||
silent: !(
|
||||
database.debug ??
|
||||
process.env.NODE_ENV?.startsWith("dev") ??
|
||||
false
|
||||
),
|
||||
},
|
||||
schemaGenerator: {
|
||||
disableForeignKeys: false,
|
||||
},
|
||||
pool: {
|
||||
min: 2,
|
||||
...database.pool,
|
||||
},
|
||||
})
|
||||
const { MikroORM, defineConfig } = await import("@mikro-orm/postgresql")
|
||||
return await MikroORM.init(
|
||||
defineConfig({
|
||||
discovery: { disableDynamicFileAccess: true, warnWhenNoEntities: false },
|
||||
entities,
|
||||
debug: database.debug ?? process.env.NODE_ENV?.startsWith("dev") ?? false,
|
||||
baseDir: process.cwd(),
|
||||
clientUrl,
|
||||
schema,
|
||||
driverOptions,
|
||||
tsNode: process.env.APP_ENV === "development",
|
||||
filters: database.filters ?? {},
|
||||
assign: {
|
||||
convertCustomTypes: true,
|
||||
},
|
||||
migrations: {
|
||||
disableForeignKeys: false,
|
||||
path: pathToMigrations,
|
||||
generator: CustomTsMigrationGenerator,
|
||||
silent: !(
|
||||
database.debug ??
|
||||
process.env.NODE_ENV?.startsWith("dev") ??
|
||||
false
|
||||
),
|
||||
},
|
||||
schemaGenerator: {
|
||||
disableForeignKeys: false,
|
||||
},
|
||||
pool: {
|
||||
min: 2,
|
||||
...database.pool,
|
||||
},
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
@@ -4,23 +4,20 @@ import type {
|
||||
FindOneOptions,
|
||||
FindOptions,
|
||||
} from "@mikro-orm/core"
|
||||
import { EntityMetadata, EntitySchema, ReferenceType } from "@mikro-orm/core"
|
||||
import { EntityMetadata, ReferenceKind } from "@mikro-orm/core"
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
|
||||
export const FreeTextSearchFilterKey = "freeTextSearch"
|
||||
export const FreeTextSearchFilterKeyPrefix = "freeTextSearch_"
|
||||
|
||||
interface FilterArgument {
|
||||
value: string
|
||||
fromEntity: string
|
||||
}
|
||||
|
||||
function getEntityProperties(entity: EntityClass<any> | EntitySchema): {
|
||||
function getEntityProperties(metadata: EntityMetadata<any>): {
|
||||
[key: string]: EntityProperty<any>
|
||||
} {
|
||||
return (
|
||||
(entity as EntityClass<any>)?.prototype.__meta?.properties ??
|
||||
(entity as EntitySchema).meta?.properties
|
||||
)
|
||||
return metadata.properties
|
||||
}
|
||||
|
||||
function retrieveRelationsConstraints(
|
||||
@@ -31,7 +28,7 @@ function retrieveRelationsConstraints(
|
||||
type: string
|
||||
name: string
|
||||
},
|
||||
models: (EntityClass<any> | EntitySchema)[],
|
||||
metadata: EntityMetadata<any>,
|
||||
searchValue: string,
|
||||
visited: Set<string> = new Set(),
|
||||
shouldStop: boolean = false
|
||||
@@ -46,13 +43,12 @@ function retrieveRelationsConstraints(
|
||||
|
||||
const relationFreeTextSearchWhere: any = []
|
||||
|
||||
const relationClass = models.find((m) => m.name === relation.type)!
|
||||
const relationProperties = getEntityProperties(relationClass)
|
||||
const relationProperties = getEntityProperties(metadata)
|
||||
|
||||
for (const propertyConfiguration of Object.values(relationProperties)) {
|
||||
if (
|
||||
!(propertyConfiguration as any).searchable ||
|
||||
propertyConfiguration.reference !== ReferenceType.SCALAR
|
||||
propertyConfiguration.kind !== ReferenceKind.SCALAR
|
||||
) {
|
||||
continue
|
||||
}
|
||||
@@ -69,9 +65,7 @@ function retrieveRelationsConstraints(
|
||||
})
|
||||
}
|
||||
|
||||
const innerRelations: EntityProperty[] =
|
||||
(relationClass as EntityClass<any>)?.prototype.__meta?.relations ??
|
||||
(relationClass as EntitySchema).meta?.relations
|
||||
const innerRelations: EntityProperty[] = metadata.relations
|
||||
|
||||
for (const innerRelation of innerRelations) {
|
||||
const branchVisited = new Set(Array.from(visited))
|
||||
@@ -108,7 +102,7 @@ function retrieveRelationsConstraints(
|
||||
mapToPk: innerRelation.mapToPk,
|
||||
type: innerRelation.type,
|
||||
},
|
||||
models,
|
||||
innerRelation.targetMeta!,
|
||||
searchValue,
|
||||
branchVisited,
|
||||
isSelfCircularDependency
|
||||
@@ -128,10 +122,9 @@ function retrieveRelationsConstraints(
|
||||
return relationFreeTextSearchWhere
|
||||
}
|
||||
|
||||
export const mikroOrmFreeTextSearchFilterOptionsFactory = (
|
||||
models: (EntityClass<any> | EntitySchema)[]
|
||||
) => {
|
||||
export const mikroOrmFreeTextSearchFilterOptionsFactory = (model: string) => {
|
||||
return {
|
||||
name: FreeTextSearchFilterKeyPrefix + model,
|
||||
cond: (
|
||||
freeTextSearchArgs: FilterArgument,
|
||||
operation: string,
|
||||
@@ -144,7 +137,7 @@ export const mikroOrmFreeTextSearchFilterOptionsFactory = (
|
||||
return {}
|
||||
}
|
||||
|
||||
const { value, fromEntity } = freeTextSearchArgs
|
||||
const { value } = freeTextSearchArgs
|
||||
|
||||
if (options?.visited?.size) {
|
||||
/**
|
||||
@@ -158,17 +151,17 @@ export const mikroOrmFreeTextSearchFilterOptionsFactory = (
|
||||
}
|
||||
}
|
||||
|
||||
const entityMetadata = manager.getDriver().getMetadata().get(fromEntity)
|
||||
const entityMetadata = manager.getDriver().getMetadata().get(model)
|
||||
|
||||
const freeTextSearchWhere = retrieveRelationsConstraints(
|
||||
{
|
||||
targetMeta: entityMetadata,
|
||||
mapToPk: false,
|
||||
searchable: true,
|
||||
type: fromEntity,
|
||||
type: model,
|
||||
name: entityMetadata.name!,
|
||||
},
|
||||
models,
|
||||
entityMetadata,
|
||||
value
|
||||
)
|
||||
|
||||
@@ -180,8 +173,5 @@ export const mikroOrmFreeTextSearchFilterOptionsFactory = (
|
||||
$or: freeTextSearchWhere,
|
||||
}
|
||||
},
|
||||
default: true,
|
||||
args: false,
|
||||
entity: models.map((m) => m.name) as string[],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
LoadStrategy,
|
||||
FilterQuery as MikroFilterQuery,
|
||||
FindOptions as MikroOptions,
|
||||
ReferenceType,
|
||||
ReferenceKind,
|
||||
} from "@mikro-orm/core"
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import {
|
||||
@@ -245,24 +245,6 @@ export class MikroOrmBaseRepository<const T extends object = object>
|
||||
|
||||
return [entities, softDeletedEntitiesMap]
|
||||
}
|
||||
|
||||
applyFreeTextSearchFilters<T>(
|
||||
findOptions: DAL.FindOptions<T & { q?: string }>,
|
||||
retrieveConstraintsToApply: (q: string) => any[]
|
||||
): void {
|
||||
if (!("q" in findOptions.where) || !findOptions.where.q) {
|
||||
delete findOptions.where.q
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const q = findOptions.where.q as string
|
||||
delete findOptions.where.q
|
||||
|
||||
findOptions.where = {
|
||||
$and: [findOptions.where, { $or: retrieveConstraintsToApply(q) }],
|
||||
} as unknown as DAL.FindOptions<T & { q?: string }>["where"]
|
||||
}
|
||||
}
|
||||
|
||||
export class MikroOrmBaseTreeRepository<
|
||||
@@ -391,7 +373,7 @@ export function mikroOrmBaseRepositoryFactory<const T extends object>(
|
||||
const relation = relations.find((relation) => relation.name === key)
|
||||
const shouldInit =
|
||||
relation &&
|
||||
relation.reference === ReferenceType.MANY_TO_MANY &&
|
||||
relation.kind === ReferenceKind.MANY_TO_MANY &&
|
||||
Array.isArray(update[key]) &&
|
||||
!update[key].length
|
||||
|
||||
@@ -434,7 +416,9 @@ export function mikroOrmBaseRepositoryFactory<const T extends object>(
|
||||
await this.initManyToManyToDetachAllItemsIfNeeded(data, context)
|
||||
|
||||
data.map((_, index) => {
|
||||
manager.assign(data[index].entity, data[index].update)
|
||||
manager.assign(data[index].entity, data[index].update, {
|
||||
mergeObjectProperties: true,
|
||||
})
|
||||
manager.persist(data[index].entity)
|
||||
})
|
||||
|
||||
@@ -578,7 +562,7 @@ export function mikroOrmBaseRepositoryFactory<const T extends object>(
|
||||
const existingEntity = existingEntitiesMap.get(key)
|
||||
if (existingEntity) {
|
||||
const updatedType = manager.assign(existingEntity, data_)
|
||||
updatedEntities.push(updatedType)
|
||||
updatedEntities.push(updatedType as any)
|
||||
} else {
|
||||
const newEntity = manager.create(this.entity, data_)
|
||||
createdEntities.push(newEntity as InferRepositoryReturnType<T>)
|
||||
@@ -698,8 +682,8 @@ export function mikroOrmBaseRepositoryFactory<const T extends object>(
|
||||
// TODO: Handle ONE_TO_ONE
|
||||
// One to one and Many to one are handled outside of the assignment as they need to happen before the main entity is created
|
||||
if (
|
||||
relation.reference === ReferenceType.ONE_TO_ONE ||
|
||||
relation.reference === ReferenceType.MANY_TO_ONE
|
||||
relation.kind === ReferenceKind.ONE_TO_ONE ||
|
||||
relation.kind === ReferenceKind.MANY_TO_ONE
|
||||
) {
|
||||
return
|
||||
}
|
||||
@@ -765,7 +749,7 @@ export function mikroOrmBaseRepositoryFactory<const T extends object>(
|
||||
return this.getEntityWithId(manager, relation.type, normalizedItem)
|
||||
})
|
||||
|
||||
if (relation.reference === ReferenceType.MANY_TO_MANY) {
|
||||
if (relation.kind === ReferenceKind.MANY_TO_MANY) {
|
||||
const currentPivotColumn = relation.inverseJoinColumns[0]
|
||||
const parentPivotColumn = relation.joinColumns[0]
|
||||
|
||||
@@ -805,7 +789,7 @@ export function mikroOrmBaseRepositoryFactory<const T extends object>(
|
||||
return { entities: normalizedData, performedActions }
|
||||
}
|
||||
|
||||
if (relation.reference === ReferenceType.ONE_TO_MANY) {
|
||||
if (relation.kind === ReferenceKind.ONE_TO_MANY) {
|
||||
const joinColumns =
|
||||
relation.targetMeta?.properties[relation.mappedBy]?.joinColumns
|
||||
|
||||
@@ -815,7 +799,7 @@ export function mikroOrmBaseRepositoryFactory<const T extends object>(
|
||||
joinColumnsConstraints[joinColumn] = data[referencedColumnName]
|
||||
})
|
||||
|
||||
const toDeleteEntities = await manager.find<any>(
|
||||
const toDeleteEntities = await manager.find<any, any, "id">(
|
||||
relation.type,
|
||||
{
|
||||
...joinColumnsConstraints,
|
||||
@@ -869,7 +853,7 @@ export function mikroOrmBaseRepositoryFactory<const T extends object>(
|
||||
}
|
||||
|
||||
// If it is a many-to-one we ensure the ID is set for when we want to set/unset an association
|
||||
if (relation.reference === ReferenceType.MANY_TO_ONE) {
|
||||
if (relation.kind === ReferenceKind.MANY_TO_ONE) {
|
||||
if (originalData === null) {
|
||||
entryCopy[relation.joinColumns[0]] = null
|
||||
return null
|
||||
@@ -927,7 +911,7 @@ export function mikroOrmBaseRepositoryFactory<const T extends object>(
|
||||
.filter(
|
||||
([_, propDef]: any) =>
|
||||
propDef.persist === false &&
|
||||
propDef.reference === ReferenceType.MANY_TO_ONE
|
||||
propDef.kind === ReferenceKind.MANY_TO_ONE
|
||||
)
|
||||
.forEach(([key]) => {
|
||||
delete resp[key]
|
||||
|
||||
@@ -7,36 +7,45 @@ import {
|
||||
Loaded,
|
||||
Platform,
|
||||
Reference,
|
||||
ReferenceType,
|
||||
ReferenceKind,
|
||||
SerializationContext,
|
||||
SerializeOptions,
|
||||
Utils,
|
||||
} from "@mikro-orm/core"
|
||||
|
||||
type CustomSerializeOptions<T, P = any> = SerializeOptions<T, P & string> & {
|
||||
preventCircularRef?: boolean
|
||||
populate?: [keyof T][] | boolean
|
||||
}
|
||||
|
||||
function isVisible<T extends object>(
|
||||
meta: EntityMetadata<T>,
|
||||
propName: string,
|
||||
options: SerializeOptions<T, any> & { preventCircularRef?: boolean } = {}
|
||||
options: CustomSerializeOptions<T> = {}
|
||||
): boolean {
|
||||
if (options.populate === true) {
|
||||
return options.populate
|
||||
return true
|
||||
}
|
||||
|
||||
if (
|
||||
Array.isArray(options.populate) &&
|
||||
options.populate?.find(
|
||||
options.exclude?.find((item) => item === propName)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (
|
||||
Array.isArray(options.populate) &&
|
||||
(options.populate?.find(
|
||||
(item) => item === propName || item.startsWith(propName + ".")
|
||||
)
|
||||
) ||
|
||||
options.populate.includes("*"))
|
||||
) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (options.exclude?.find((item) => item === propName)) {
|
||||
return false
|
||||
}
|
||||
|
||||
const prop = meta.properties[propName]
|
||||
const visible = prop && !prop.hidden
|
||||
const visible = (prop && !prop.hidden) || prop === undefined // allow unknown properties
|
||||
const prefixed = prop && !prop.primary && propName.startsWith("_") // ignore prefixed properties, if it's not a PK
|
||||
|
||||
return visible && !prefixed
|
||||
@@ -45,13 +54,14 @@ function isVisible<T extends object>(
|
||||
function isPopulated<T extends object>(
|
||||
entity: T,
|
||||
propName: string,
|
||||
options: SerializeOptions<T, any>
|
||||
options: CustomSerializeOptions<T>
|
||||
): boolean {
|
||||
if (
|
||||
typeof options.populate !== "boolean" &&
|
||||
options.populate?.find(
|
||||
Array.isArray(options.populate) &&
|
||||
(options.populate?.find(
|
||||
(item) => item === propName || item.startsWith(propName + ".")
|
||||
)
|
||||
) ||
|
||||
options.populate.includes("*"))
|
||||
) {
|
||||
return true
|
||||
}
|
||||
@@ -78,9 +88,7 @@ function filterEntityPropToSerialize({
|
||||
}: {
|
||||
propName: string
|
||||
meta: EntityMetadata
|
||||
options: SerializeOptions<object, any> & {
|
||||
preventCircularRef?: boolean
|
||||
}
|
||||
options: CustomSerializeOptions<any>
|
||||
parents?: string[]
|
||||
}): boolean {
|
||||
parents ??= []
|
||||
@@ -92,7 +100,7 @@ function filterEntityPropToSerialize({
|
||||
prop &&
|
||||
options.preventCircularRef &&
|
||||
isVisibleRes &&
|
||||
prop.reference !== ReferenceType.SCALAR
|
||||
prop.kind !== ReferenceKind.SCALAR
|
||||
) {
|
||||
// mapToPk would represent a foreign key and we want to keep them
|
||||
if (!!prop.mapToPk) {
|
||||
@@ -108,7 +116,7 @@ function filterEntityPropToSerialize({
|
||||
export class EntitySerializer {
|
||||
static serialize<T extends object, P extends string = never>(
|
||||
entity: T,
|
||||
options: SerializeOptions<T, P> & { preventCircularRef?: boolean } = {},
|
||||
options: CustomSerializeOptions<T, P> = {},
|
||||
parents: string[] = []
|
||||
): EntityDTO<Loaded<T, P>> {
|
||||
const parents_ = Array.from(new Set(parents))
|
||||
@@ -118,12 +126,11 @@ export class EntitySerializer {
|
||||
let contextCreated = false
|
||||
|
||||
if (!wrapped.__serializationContext.root) {
|
||||
const root = new SerializationContext<T>()
|
||||
const root = new SerializationContext<T>({} as any)
|
||||
SerializationContext.propagate(
|
||||
root,
|
||||
entity,
|
||||
(meta, prop) =>
|
||||
meta.properties[prop]?.reference !== ReferenceType.SCALAR
|
||||
(meta, prop) => meta.properties[prop]?.kind !== ReferenceKind.SCALAR
|
||||
)
|
||||
contextCreated = true
|
||||
}
|
||||
@@ -238,25 +245,25 @@ export class EntitySerializer {
|
||||
|
||||
private static propertyName<T>(
|
||||
meta: EntityMetadata<T>,
|
||||
prop: keyof T & string,
|
||||
prop: string,
|
||||
platform?: Platform
|
||||
): string {
|
||||
/* istanbul ignore next */
|
||||
if (meta.properties[prop]?.serializedName) {
|
||||
return meta.properties[prop].serializedName as keyof T & string
|
||||
return meta.properties[prop].serializedName as string
|
||||
}
|
||||
|
||||
if (meta.properties[prop]?.primary && platform) {
|
||||
return platform.getSerializedPrimaryKeyField(prop) as keyof T & string
|
||||
return platform.getSerializedPrimaryKeyField(prop) as string
|
||||
}
|
||||
|
||||
return prop
|
||||
}
|
||||
|
||||
private static processProperty<T extends object>(
|
||||
prop: keyof T & string,
|
||||
prop: string,
|
||||
entity: T,
|
||||
options: SerializeOptions<T, any>,
|
||||
options: CustomSerializeOptions<T>,
|
||||
parents: string[] = []
|
||||
): T[keyof T] | undefined {
|
||||
const parents_ = [...parents, entity.constructor.name]
|
||||
@@ -284,12 +291,17 @@ export class EntitySerializer {
|
||||
}
|
||||
|
||||
if (Utils.isCollection(entity[prop])) {
|
||||
return this.processCollection(prop, entity, options, parents_)
|
||||
return this.processCollection(
|
||||
prop as keyof T & string,
|
||||
entity,
|
||||
options,
|
||||
parents_
|
||||
)
|
||||
}
|
||||
|
||||
if (Utils.isEntity(entity[prop], true)) {
|
||||
return this.processEntity(
|
||||
prop,
|
||||
prop as keyof T & string,
|
||||
entity,
|
||||
wrapped.__platform,
|
||||
options,
|
||||
@@ -298,7 +310,7 @@ export class EntitySerializer {
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (property?.reference === ReferenceType.EMBEDDED) {
|
||||
if (property?.reference === ReferenceKind.EMBEDDED) {
|
||||
if (Array.isArray(entity[prop])) {
|
||||
return (entity[prop] as object[]).map((item) =>
|
||||
helper(item).toJSON()
|
||||
@@ -322,9 +334,9 @@ export class EntitySerializer {
|
||||
}
|
||||
|
||||
private static extractChildOptions<T extends object, U extends object>(
|
||||
options: SerializeOptions<T, any>,
|
||||
options: CustomSerializeOptions<T>,
|
||||
prop: keyof T & string
|
||||
): SerializeOptions<U, any> {
|
||||
): CustomSerializeOptions<U> {
|
||||
const extractChildElements = (items: string[]) => {
|
||||
return items
|
||||
.filter((field) => field.startsWith(`${prop}.`))
|
||||
@@ -333,20 +345,22 @@ export class EntitySerializer {
|
||||
|
||||
return {
|
||||
...options,
|
||||
populate: Array.isArray(options.populate)
|
||||
? extractChildElements(options.populate)
|
||||
: options.populate,
|
||||
exclude: Array.isArray(options.exclude)
|
||||
? extractChildElements(options.exclude)
|
||||
: options.exclude,
|
||||
} as SerializeOptions<U, any>
|
||||
populate:
|
||||
Array.isArray(options.populate) && !options.populate.includes("*")
|
||||
? extractChildElements(options.populate as unknown as string[])
|
||||
: options.populate,
|
||||
exclude:
|
||||
Array.isArray(options.exclude) && !options.exclude.includes("*")
|
||||
? extractChildElements(options.exclude)
|
||||
: options.exclude,
|
||||
} as CustomSerializeOptions<U>
|
||||
}
|
||||
|
||||
private static processEntity<T extends object>(
|
||||
prop: keyof T & string,
|
||||
entity: T,
|
||||
platform: Platform,
|
||||
options: SerializeOptions<T, any>,
|
||||
options: CustomSerializeOptions<T>,
|
||||
parents: string[] = []
|
||||
): T[keyof T] | undefined {
|
||||
const parents_ = [...parents, entity.constructor.name]
|
||||
@@ -373,7 +387,7 @@ export class EntitySerializer {
|
||||
private static processCollection<T extends object>(
|
||||
prop: keyof T & string,
|
||||
entity: T,
|
||||
options: SerializeOptions<T, any>,
|
||||
options: CustomSerializeOptions<T>,
|
||||
parents: string[] = []
|
||||
): T[keyof T] | undefined {
|
||||
const parents_ = [...parents, entity.constructor.name]
|
||||
@@ -401,6 +415,7 @@ export const mikroOrmSerializer = <TOutput extends object>(
|
||||
data: any,
|
||||
options?: Parameters<typeof EntitySerializer.serialize>[1] & {
|
||||
preventCircularRef?: boolean
|
||||
populate?: string[] | boolean
|
||||
}
|
||||
): Promise<TOutput> => {
|
||||
return new Promise<TOutput>((resolve) => {
|
||||
@@ -422,10 +437,11 @@ export const mikroOrmSerializer = <TOutput extends object>(
|
||||
let result: any = forSerialization.map((entity) =>
|
||||
EntitySerializer.serialize(entity, {
|
||||
forceObject: true,
|
||||
populate: true,
|
||||
populate: ["*"],
|
||||
|
||||
preventCircularRef: true,
|
||||
...options,
|
||||
} as SerializeOptions<any, any>)
|
||||
} as CustomSerializeOptions<any>)
|
||||
) as TOutput[]
|
||||
|
||||
if (notForSerialization.length) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,6 +6,7 @@ import {
|
||||
import { DmlEntity, DMLEntitySchemaBuilder } from "./entity"
|
||||
import { createBigNumberProperties } from "./helpers/entity-builder/create-big-number-properties"
|
||||
import { createDefaultProperties } from "./helpers/entity-builder/create-default-properties"
|
||||
import { FloatProperty } from "./properties"
|
||||
import { ArrayProperty } from "./properties/array"
|
||||
import { AutoIncrementProperty } from "./properties/autoincrement"
|
||||
import { BigNumberProperty } from "./properties/big-number"
|
||||
@@ -21,7 +22,6 @@ import { HasMany } from "./relations/has-many"
|
||||
import { HasOne } from "./relations/has-one"
|
||||
import { HasOneWithForeignKey } from "./relations/has-one-fk"
|
||||
import { ManyToMany } from "./relations/many-to-many"
|
||||
import { FloatProperty } from "./properties"
|
||||
|
||||
/**
|
||||
* The implicit properties added by EntityBuilder in every schema
|
||||
@@ -128,7 +128,7 @@ export class EntityBuilder {
|
||||
): DmlEntity<DMLEntitySchemaBuilder<Schema>, TConfig> {
|
||||
this.#disallowImplicitProperties(schema)
|
||||
|
||||
return new DmlEntity<Schema, TConfig>(nameOrConfig, {
|
||||
return new DmlEntity(nameOrConfig, {
|
||||
...schema,
|
||||
...createBigNumberProperties(schema),
|
||||
...createDefaultProperties(),
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
import {
|
||||
IDmlEntity,
|
||||
DMLSchema,
|
||||
EntityIndex,
|
||||
CheckConstraint,
|
||||
DMLSchema,
|
||||
EntityCascades,
|
||||
QueryCondition,
|
||||
IDmlEntityConfig,
|
||||
EntityIndex,
|
||||
ExtractEntityRelations,
|
||||
IDmlEntity,
|
||||
IDmlEntityConfig,
|
||||
InferDmlEntityNameFromConfig,
|
||||
QueryCondition,
|
||||
} from "@medusajs/types"
|
||||
import { isObject, isString, toCamelCase, upperCaseFirst } from "../common"
|
||||
import { transformIndexWhere } from "./helpers/entity-builder/build-indexes"
|
||||
import { DMLSchemaWithBigNumber } from "./helpers/entity-builder/create-big-number-properties"
|
||||
import { DMLSchemaDefaults } from "./helpers/entity-builder/create-default-properties"
|
||||
import { BelongsTo } from "./relations/belongs-to"
|
||||
import {
|
||||
DMLSchemaDefaults,
|
||||
DMLSchemaWithBigNumber,
|
||||
} from "./helpers/entity-builder"
|
||||
|
||||
const IsDmlEntity = Symbol.for("isDmlEntity")
|
||||
|
||||
@@ -68,7 +66,7 @@ function extractNameAndTableName<const Config extends IDmlEntityConfig>(
|
||||
* name, its schema and relationships.
|
||||
*/
|
||||
export class DmlEntity<
|
||||
Schema extends DMLSchema,
|
||||
const Schema extends DMLSchema,
|
||||
const TConfig extends IDmlEntityConfig
|
||||
> implements IDmlEntity<Schema, TConfig>
|
||||
{
|
||||
@@ -79,6 +77,7 @@ export class DmlEntity<
|
||||
|
||||
readonly #tableName: string
|
||||
#cascades: EntityCascades<string[], string[]> = {}
|
||||
|
||||
#indexes: EntityIndex<Schema>[] = []
|
||||
#checks: CheckConstraint<Schema>[] = []
|
||||
|
||||
@@ -251,8 +250,6 @@ export class DmlEntity<
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
*/
|
||||
checks(checks: CheckConstraint<Schema>[]) {
|
||||
this.#checks = checks
|
||||
return this
|
||||
|
||||
@@ -8,15 +8,18 @@ import type {
|
||||
} from "@medusajs/types"
|
||||
import { Entity, Filter } from "@mikro-orm/core"
|
||||
|
||||
import {
|
||||
mikroOrmFreeTextSearchFilterOptionsFactory,
|
||||
mikroOrmSoftDeletableFilterOptions,
|
||||
} from "../../dal"
|
||||
import { DmlEntity } from "../entity"
|
||||
import { IdProperty } from "../properties/id"
|
||||
import { DuplicateIdPropertyError } from "../errors"
|
||||
import { applyChecks } from "./mikro-orm/apply-checks"
|
||||
import { mikroOrmSoftDeletableFilterOptions } from "../../dal"
|
||||
import { defineProperty } from "./entity-builder/define-property"
|
||||
import { IdProperty } from "../properties/id"
|
||||
import { applySearchable } from "./entity-builder/apply-searchable"
|
||||
import { parseEntityName } from "./entity-builder/parse-entity-name"
|
||||
import { defineProperty } from "./entity-builder/define-property"
|
||||
import { defineRelationship } from "./entity-builder/define-relationship"
|
||||
import { parseEntityName } from "./entity-builder/parse-entity-name"
|
||||
import { applyChecks } from "./mikro-orm/apply-checks"
|
||||
import { applyEntityIndexes, applyIndexes } from "./mikro-orm/apply-indexes"
|
||||
|
||||
/**
|
||||
@@ -48,8 +51,16 @@ function createMikrORMEntity() {
|
||||
function createEntity<T extends DmlEntity<any, any>>(entity: T): Infer<T> {
|
||||
class MikroORMEntity {}
|
||||
|
||||
const { schema, cascades, indexes: entityIndexes, checks } = entity.parse()
|
||||
const {
|
||||
schema,
|
||||
cascades,
|
||||
indexes: entityIndexes = [],
|
||||
//params,
|
||||
checks,
|
||||
} = entity.parse()
|
||||
|
||||
const { modelName, tableName } = parseEntityName(entity)
|
||||
|
||||
if (ENTITIES[modelName]) {
|
||||
return ENTITIES[modelName] as Infer<T>
|
||||
}
|
||||
@@ -102,6 +113,9 @@ function createMikrORMEntity() {
|
||||
/**
|
||||
* Converting class to a MikroORM entity
|
||||
*/
|
||||
Filter(mikroOrmFreeTextSearchFilterOptionsFactory(modelName))(
|
||||
MikroORMEntity
|
||||
)
|
||||
const RegisteredEntity = Entity({ tableName })(
|
||||
Filter(mikroOrmSoftDeletableFilterOptions)(MikroORMEntity)
|
||||
) as Infer<T>
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
PrimaryKey,
|
||||
Property,
|
||||
Utils,
|
||||
t as mikroOrmType,
|
||||
} from "@mikro-orm/core"
|
||||
import { generateEntityId, isDefined } from "../../../common"
|
||||
import { MikroOrmBigNumberProperty } from "../../../dal"
|
||||
@@ -122,7 +121,8 @@ export function defineProperty(
|
||||
) {
|
||||
const field = property.parse(propertyName)
|
||||
/**
|
||||
* Here we initialize nullable properties with a null value
|
||||
* Here we initialize all properties with their default values on before create
|
||||
* which means when persist is called but not necessarely flush
|
||||
*/
|
||||
if (isDefined(field.defaultValue) || field.nullable) {
|
||||
const defaultValueSetterHookName = `${field.fieldName}_setDefaultValueOnBeforeCreate`
|
||||
@@ -274,11 +274,12 @@ export function defineProperty(
|
||||
: Property
|
||||
|
||||
Prop({
|
||||
columnType: "serial",
|
||||
type: mikroOrmType.integer,
|
||||
nullable: true,
|
||||
autoincrement: true,
|
||||
type: "number",
|
||||
runtimeType: "number",
|
||||
nullable: field.nullable,
|
||||
fieldName: field.fieldName,
|
||||
serializer: Number,
|
||||
serializer: (value) => (value == null ? value : Number(value)),
|
||||
})(MikroORMEntity.prototype, field.fieldName)
|
||||
return
|
||||
}
|
||||
@@ -290,13 +291,14 @@ export function defineProperty(
|
||||
Property({
|
||||
columnType: "real",
|
||||
type: "number",
|
||||
runtimeType: "number",
|
||||
nullable: field.nullable,
|
||||
fieldName: field.fieldName,
|
||||
/**
|
||||
* Applying number serializer to convert value back to a
|
||||
* JavaScript number
|
||||
*/
|
||||
serializer: Number,
|
||||
serializer: (value) => (value == null ? value : Number(value)),
|
||||
/**
|
||||
* MikroORM does not ignore undefined values for default when generating
|
||||
* the database schema SQL. Conditionally add it here to prevent undefined
|
||||
|
||||
@@ -162,7 +162,7 @@ export function defineHasOneRelationship(
|
||||
entity: relatedModelName,
|
||||
...(relationship.nullable ? { nullable: relationship.nullable } : {}),
|
||||
...(mappedBy ? { mappedBy } : {}),
|
||||
onDelete: shouldRemoveRelated ? "cascade" : undefined,
|
||||
deleteRule: shouldRemoveRelated ? "cascade" : undefined,
|
||||
} as OneToOneOptions<any, any>
|
||||
|
||||
if (shouldRemoveRelated && !isOthersideBelongsTo) {
|
||||
@@ -322,7 +322,7 @@ export function defineBelongsToRelationship(
|
||||
/**
|
||||
* In DML the relationships are cascaded from parent to child. A belongsTo
|
||||
* relationship is always a child, therefore we look at the parent and
|
||||
* define a onDelete: cascade when we are included in the delete
|
||||
* define a deleteRule: cascade when we are included in the delete
|
||||
* list of parent cascade.
|
||||
*/
|
||||
const shouldCascade = !!relationCascades.delete?.includes(mappedBy)
|
||||
@@ -435,27 +435,33 @@ export function defineBelongsToRelationship(
|
||||
|
||||
if (DmlManyToMany.isManyToMany(otherSideRelation)) {
|
||||
Property({
|
||||
type: relatedModelName,
|
||||
type: "string",
|
||||
columnType: "text",
|
||||
fieldName: foreignKeyName,
|
||||
nullable: relationship.nullable,
|
||||
})(MikroORMEntity.prototype, foreignKeyName)
|
||||
|
||||
ManyToOne({
|
||||
const conf = {
|
||||
entity: relatedModelName,
|
||||
nullable: relationship.nullable,
|
||||
persist: false,
|
||||
onDelete: shouldCascade || detachCascade ? "cascade" : undefined,
|
||||
})(MikroORMEntity.prototype, relationship.name)
|
||||
}
|
||||
if (shouldCascade || detachCascade) {
|
||||
conf["deleteRule"] = "cascade"
|
||||
}
|
||||
ManyToOne(conf)(MikroORMEntity.prototype, relationship.name)
|
||||
} else {
|
||||
ManyToOne({
|
||||
const conf = {
|
||||
entity: relatedModelName,
|
||||
columnType: "text",
|
||||
mapToPk: true,
|
||||
fieldName: foreignKeyName,
|
||||
nullable: relationship.nullable,
|
||||
onDelete: shouldCascade ? "cascade" : undefined,
|
||||
})(MikroORMEntity.prototype, foreignKeyName)
|
||||
}
|
||||
if (shouldCascade) {
|
||||
conf["deleteRule"] = "cascade"
|
||||
}
|
||||
ManyToOne(conf)(MikroORMEntity.prototype, foreignKeyName)
|
||||
|
||||
ManyToOne({
|
||||
entity: relatedModelName,
|
||||
@@ -486,7 +492,6 @@ export function defineBelongsToRelationship(
|
||||
const foreignKeyName =
|
||||
relationship.options.foreignKeyName ??
|
||||
camelToSnakeCase(`${relationship.name}Id`)
|
||||
|
||||
Property({
|
||||
columnType: "text",
|
||||
type: "string",
|
||||
@@ -504,10 +509,10 @@ export function defineBelongsToRelationship(
|
||||
fieldName: foreignKeyName,
|
||||
owner: true,
|
||||
// orphanRemoval: true,
|
||||
onDelete: shouldCascade ? "cascade" : undefined,
|
||||
}
|
||||
|
||||
if (shouldCascade) {
|
||||
oneToOneOptions.deleteRule = "cascade"
|
||||
oneToOneOptions.cascade = [Cascade.PERSIST, "soft-remove"] as any
|
||||
}
|
||||
|
||||
@@ -741,8 +746,15 @@ export function defineManyToManyRelationship(
|
||||
: {}),
|
||||
...(pivotEntityName ? { pivotEntity: pivotEntityName } : {}),
|
||||
...({ [mappedByProp]: mappedByPropValue } as any),
|
||||
[joinColumnProp]: joinColumn ?? joinColumns,
|
||||
[inverseJoinColumnProp]: inverseJoinColumn ?? inverseJoinColumns,
|
||||
} as any
|
||||
|
||||
if (joinColumn || joinColumns) {
|
||||
manytoManyOptions[joinColumnProp] = joinColumn ?? joinColumns
|
||||
}
|
||||
|
||||
if (inverseJoinColumn || inverseJoinColumns) {
|
||||
manytoManyOptions[inverseJoinColumnProp] =
|
||||
inverseJoinColumn ?? inverseJoinColumns
|
||||
}
|
||||
|
||||
ManyToMany(manytoManyOptions)(MikroORMEntity.prototype, relationship.name)
|
||||
|
||||
@@ -4,3 +4,5 @@ export * from "./helpers/entity-builder/index"
|
||||
export * from "./helpers/create-mikro-orm-entity"
|
||||
export * from "./relations/index"
|
||||
export * from "./properties/index"
|
||||
|
||||
export * from "./helpers/entity-builder/index"
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { EntityConstructor } from "@medusajs/types"
|
||||
import { MetadataStorage, MikroORM } from "@mikro-orm/core"
|
||||
import { defineConfig } from "@mikro-orm/postgresql"
|
||||
import { join } from "path"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
import { FileSystem } from "../../../common"
|
||||
import { CustomTsMigrationGenerator, mikroOrmSerializer } from "../../../dal"
|
||||
import { model } from "../../entity-builder"
|
||||
import {
|
||||
mikroORMEntityBuilder,
|
||||
toMikroOrmEntities,
|
||||
} from "../../helpers/create-mikro-orm-entity"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
import { CustomTsMigrationGenerator, mikroOrmSerializer } from "../../../dal"
|
||||
import { EntityConstructor } from "@medusajs/types"
|
||||
import { pgGodCredentials } from "../utils"
|
||||
import { FileSystem } from "../../../common"
|
||||
import { join } from "path"
|
||||
|
||||
export const fileSystem = new FileSystem(
|
||||
join(__dirname, "../../integration-tests-migrations-enum")
|
||||
@@ -40,19 +41,20 @@ describe("EntityBuilder", () => {
|
||||
|
||||
await createDatabase({ databaseName: dbName }, pgGodCredentials)
|
||||
|
||||
orm = await MikroORM.init({
|
||||
entities: [User],
|
||||
tsNode: true,
|
||||
dbName,
|
||||
password: pgGodCredentials.password,
|
||||
host: pgGodCredentials.host,
|
||||
user: pgGodCredentials.user,
|
||||
type: "postgresql",
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
path: fileSystem.basePath,
|
||||
},
|
||||
})
|
||||
orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [User],
|
||||
tsNode: true,
|
||||
dbName,
|
||||
password: pgGodCredentials.password,
|
||||
host: pgGodCredentials.host,
|
||||
user: pgGodCredentials.user,
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
path: fileSystem.basePath,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
const migrator = orm.getMigrator()
|
||||
await migrator.createMigration()
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
import { EntityConstructor } from "@medusajs/types"
|
||||
import {
|
||||
CheckConstraintViolationException,
|
||||
MetadataStorage,
|
||||
MikroORM,
|
||||
} from "@mikro-orm/core"
|
||||
import { defineConfig } from "@mikro-orm/postgresql"
|
||||
import { join } from "path"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
import { FileSystem } from "../../../common"
|
||||
import { CustomTsMigrationGenerator, mikroOrmSerializer } from "../../../dal"
|
||||
import { model } from "../../entity-builder"
|
||||
import {
|
||||
mikroORMEntityBuilder,
|
||||
toMikroOrmEntities,
|
||||
} from "../../helpers/create-mikro-orm-entity"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
import { CustomTsMigrationGenerator, mikroOrmSerializer } from "../../../dal"
|
||||
import { EntityConstructor } from "@medusajs/types"
|
||||
import { pgGodCredentials } from "../utils"
|
||||
import { FileSystem } from "../../../common"
|
||||
import { join } from "path"
|
||||
|
||||
export const fileSystem = new FileSystem(
|
||||
join(__dirname, "../../integration-tests-migrations-enum")
|
||||
@@ -43,19 +44,20 @@ describe("EntityBuilder | enum", () => {
|
||||
|
||||
await createDatabase({ databaseName: dbName }, pgGodCredentials)
|
||||
|
||||
orm = await MikroORM.init({
|
||||
entities: [User],
|
||||
tsNode: true,
|
||||
dbName,
|
||||
password: pgGodCredentials.password,
|
||||
host: pgGodCredentials.host,
|
||||
user: pgGodCredentials.user,
|
||||
type: "postgresql",
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
path: fileSystem.basePath,
|
||||
},
|
||||
})
|
||||
orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [User],
|
||||
tsNode: true,
|
||||
dbName,
|
||||
password: pgGodCredentials.password,
|
||||
host: pgGodCredentials.host,
|
||||
user: pgGodCredentials.user,
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
path: fileSystem.basePath,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
const migrator = orm.getMigrator()
|
||||
await migrator.createMigration()
|
||||
|
||||
+20
-18
@@ -1,15 +1,16 @@
|
||||
import { EntityConstructor } from "@medusajs/types"
|
||||
import { MetadataStorage, MikroORM } from "@mikro-orm/core"
|
||||
import { defineConfig } from "@mikro-orm/postgresql"
|
||||
import { join } from "path"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
import { FileSystem } from "../../../common"
|
||||
import { CustomTsMigrationGenerator, mikroOrmSerializer } from "../../../dal"
|
||||
import { model } from "../../entity-builder"
|
||||
import {
|
||||
mikroORMEntityBuilder,
|
||||
toMikroOrmEntities,
|
||||
} from "../../helpers/create-mikro-orm-entity"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
import { CustomTsMigrationGenerator, mikroOrmSerializer } from "../../../dal"
|
||||
import { EntityConstructor } from "@medusajs/types"
|
||||
import { pgGodCredentials } from "../utils"
|
||||
import { FileSystem } from "../../../common"
|
||||
import { join } from "path"
|
||||
|
||||
export const fileSystem = new FileSystem(
|
||||
join(__dirname, "../../integration-tests-migrations-has-one-belongs-to")
|
||||
@@ -45,19 +46,20 @@ describe("hasOne - belongTo", () => {
|
||||
|
||||
await createDatabase({ databaseName: dbName }, pgGodCredentials)
|
||||
|
||||
orm = await MikroORM.init({
|
||||
entities: [Team, User],
|
||||
tsNode: true,
|
||||
dbName,
|
||||
password: pgGodCredentials.password,
|
||||
host: pgGodCredentials.host,
|
||||
user: pgGodCredentials.user,
|
||||
type: "postgresql",
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
path: fileSystem.basePath,
|
||||
},
|
||||
})
|
||||
orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [Team, User],
|
||||
tsNode: true,
|
||||
dbName,
|
||||
password: pgGodCredentials.password,
|
||||
host: pgGodCredentials.host,
|
||||
user: pgGodCredentials.user,
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
path: fileSystem.basePath,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
const migrator = orm.getMigrator()
|
||||
await migrator.createMigration()
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { join } from "path"
|
||||
import { EntityConstructor } from "@medusajs/types"
|
||||
import { MetadataStorage, MikroORM } from "@mikro-orm/core"
|
||||
import { defineConfig } from "@mikro-orm/postgresql"
|
||||
import { join } from "path"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
import { FileSystem } from "../../../common"
|
||||
import { CustomTsMigrationGenerator, mikroOrmSerializer } from "../../../dal"
|
||||
import { model } from "../../entity-builder"
|
||||
import {
|
||||
mikroORMEntityBuilder,
|
||||
toMikroOrmEntities,
|
||||
} from "../../helpers/create-mikro-orm-entity"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
import { CustomTsMigrationGenerator, mikroOrmSerializer } from "../../../dal"
|
||||
import { EntityConstructor } from "@medusajs/types"
|
||||
import { pgGodCredentials } from "../utils"
|
||||
import { FileSystem } from "../../../common"
|
||||
|
||||
jest.setTimeout(30000)
|
||||
|
||||
@@ -62,19 +63,20 @@ describe("manyToMany - manyToMany", () => {
|
||||
|
||||
await createDatabase({ databaseName: dbName }, pgGodCredentials)
|
||||
|
||||
orm = await MikroORM.init({
|
||||
entities: [Team, User, Squad],
|
||||
tsNode: true,
|
||||
dbName,
|
||||
password: pgGodCredentials.password,
|
||||
host: pgGodCredentials.host,
|
||||
user: pgGodCredentials.user,
|
||||
type: "postgresql",
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
path: fileSystem.basePath,
|
||||
},
|
||||
})
|
||||
orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [Team, User, Squad],
|
||||
tsNode: true,
|
||||
dbName,
|
||||
password: pgGodCredentials.password,
|
||||
host: pgGodCredentials.host,
|
||||
user: pgGodCredentials.user,
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
path: fileSystem.basePath,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
const migrator = orm.getMigrator()
|
||||
await migrator.createMigration()
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { EntityConstructor } from "@medusajs/types"
|
||||
import { MetadataStorage, MikroORM } from "@mikro-orm/core"
|
||||
import { model } from "../../entity-builder"
|
||||
import {
|
||||
mikroORMEntityBuilder,
|
||||
toMikroOrmEntities,
|
||||
} from "../../helpers/create-mikro-orm-entity"
|
||||
import { defineConfig, SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import { join } from "path"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
import { FileSystem } from "../../../common"
|
||||
import {
|
||||
CustomTsMigrationGenerator,
|
||||
mikroOrmSerializer,
|
||||
mikroOrmUpdateDeletedAtRecursively,
|
||||
SoftDeletableFilterKey,
|
||||
} from "../../../dal"
|
||||
import { EntityConstructor } from "@medusajs/types"
|
||||
import { model } from "../../entity-builder"
|
||||
import {
|
||||
mikroORMEntityBuilder,
|
||||
toMikroOrmEntities,
|
||||
} from "../../helpers/create-mikro-orm-entity"
|
||||
import { pgGodCredentials } from "../utils"
|
||||
import { FileSystem } from "../../../common"
|
||||
import { join } from "path"
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
|
||||
export const fileSystem = new FileSystem(
|
||||
join(__dirname, "../../integration-tests-migrations-many-to-one")
|
||||
@@ -55,19 +55,20 @@ describe("manyToOne - belongTo", () => {
|
||||
|
||||
await createDatabase({ databaseName: dbName }, pgGodCredentials)
|
||||
|
||||
orm = await MikroORM.init({
|
||||
entities: [Team, User],
|
||||
tsNode: true,
|
||||
dbName,
|
||||
password: pgGodCredentials.password,
|
||||
host: pgGodCredentials.host,
|
||||
user: pgGodCredentials.user,
|
||||
type: "postgresql",
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
path: fileSystem.basePath,
|
||||
},
|
||||
})
|
||||
orm = await MikroORM.init(
|
||||
defineConfig({
|
||||
entities: [Team, User],
|
||||
tsNode: true,
|
||||
dbName,
|
||||
password: pgGodCredentials.password,
|
||||
host: pgGodCredentials.host,
|
||||
user: pgGodCredentials.user,
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
path: fileSystem.basePath,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
const migrator = orm.getMigrator()
|
||||
await migrator.createMigration()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const DB_HOST = process.env.DB_HOST ?? "localhost"
|
||||
const DB_USERNAME = process.env.DB_USERNAME ?? ""
|
||||
const DB_USERNAME = process.env.DB_USERNAME ?? "postgres"
|
||||
const DB_PASSWORD = process.env.DB_PASSWORD ?? ""
|
||||
|
||||
export const pgGodCredentials = {
|
||||
|
||||
@@ -8,7 +8,10 @@ import { PrimaryKeyModifier } from "./primary-key"
|
||||
export class NumberProperty extends BaseProperty<number> {
|
||||
protected dataType: {
|
||||
name: "number"
|
||||
options: {}
|
||||
options: {
|
||||
primaryKey?: boolean
|
||||
searchable?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -30,6 +33,27 @@ export class NumberProperty extends BaseProperty<number> {
|
||||
return new PrimaryKeyModifier<number, NumberProperty>(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* This method indicates that a number property is searchable.
|
||||
*
|
||||
* @example
|
||||
* import { model } from "@medusajs/framework/utils"
|
||||
*
|
||||
* const MyCustom = model.define("my_custom", {
|
||||
* name: model.number().searchable(),
|
||||
* // ...
|
||||
* })
|
||||
*
|
||||
* export default MyCustom
|
||||
*
|
||||
* @customNamespace Property Configuration Methods
|
||||
*/
|
||||
searchable() {
|
||||
this.dataType.options.searchable = true
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
constructor(options?: { primaryKey?: boolean }) {
|
||||
super()
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
MigrationResult,
|
||||
UmzugMigration,
|
||||
} from "@mikro-orm/migrations"
|
||||
import { PostgreSqlDriver } from "@mikro-orm/postgresql"
|
||||
import { defineConfig, PostgreSqlDriver } from "@mikro-orm/postgresql"
|
||||
import { EventEmitter } from "events"
|
||||
import { access, mkdir, writeFile } from "fs/promises"
|
||||
import { dirname } from "path"
|
||||
@@ -42,13 +42,15 @@ export class Migrations extends EventEmitter<MigrationsEvents> {
|
||||
return this.#configOrConnection as MikroORM<PostgreSqlDriver>
|
||||
}
|
||||
|
||||
return await MikroORM.init({
|
||||
...this.#configOrConnection,
|
||||
migrations: {
|
||||
...this.#configOrConnection.migrations,
|
||||
silent: true,
|
||||
},
|
||||
})
|
||||
return await MikroORM.init(
|
||||
defineConfig({
|
||||
...(this.#configOrConnection as any),
|
||||
migrations: {
|
||||
...this.#configOrConnection.migrations,
|
||||
silent: true,
|
||||
},
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+7
-7
@@ -1,13 +1,13 @@
|
||||
import { join } from "path"
|
||||
import { MikroORM } from "@mikro-orm/postgresql"
|
||||
import { MetadataStorage } from "@mikro-orm/core"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
import { TSMigrationGenerator } from "@mikro-orm/migrations"
|
||||
import { MikroORM } from "@mikro-orm/postgresql"
|
||||
import { join } from "path"
|
||||
import { createDatabase, dropDatabase } from "pg-god"
|
||||
|
||||
import { model } from "../../../dml"
|
||||
import { FileSystem } from "../../../common"
|
||||
import { Migrations, MigrationsEvents } from "../../index"
|
||||
import { model } from "../../../dml"
|
||||
import { defineMikroOrmCliConfig } from "../../../modules-sdk"
|
||||
import { Migrations, MigrationsEvents } from "../../index"
|
||||
|
||||
const DB_HOST = process.env.DB_HOST ?? "localhost"
|
||||
const DB_USERNAME = process.env.DB_USERNAME ?? ""
|
||||
@@ -22,8 +22,8 @@ const migrationFileNameGenerator = (_: string, name?: string) => {
|
||||
}
|
||||
|
||||
const pgGodCredentials = {
|
||||
user: DB_USERNAME,
|
||||
password: DB_PASSWORD,
|
||||
user: DB_USERNAME ?? "postgres",
|
||||
password: DB_PASSWORD ?? "",
|
||||
host: DB_HOST,
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -23,8 +23,8 @@ const moduleName = "myTestServiceRun"
|
||||
const fs = new FileSystem(join(__dirname, "./migrations-run"))
|
||||
|
||||
const pgGodCredentials = {
|
||||
user: DB_USERNAME,
|
||||
password: DB_PASSWORD,
|
||||
user: DB_USERNAME ?? "postgres",
|
||||
password: DB_PASSWORD ?? "",
|
||||
host: DB_HOST,
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ describe("defineMikroOrmCliConfig", () => {
|
||||
|
||||
expect(config).toEqual({
|
||||
entities: [{}],
|
||||
type: "postgresql",
|
||||
driver: expect.any(Function),
|
||||
host: "127.0.0.1",
|
||||
user: "postgres",
|
||||
password: "",
|
||||
@@ -37,7 +37,7 @@ describe("defineMikroOrmCliConfig", () => {
|
||||
|
||||
expect(config).toEqual({
|
||||
entities: [{}],
|
||||
type: "postgresql",
|
||||
driver: expect.any(Function),
|
||||
dbName: "medusa-my-test",
|
||||
host: "127.0.0.1",
|
||||
user: "postgres",
|
||||
|
||||
@@ -2,11 +2,7 @@ import { Logger, MedusaContainer, ModulesSdkTypes } from "@medusajs/types"
|
||||
import { PostgreSqlDriver, SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import { asValue } from "awilix"
|
||||
import { ContainerRegistrationKeys, MedusaError } from "../../common"
|
||||
import {
|
||||
FreeTextSearchFilterKey,
|
||||
mikroOrmCreateConnection,
|
||||
mikroOrmFreeTextSearchFilterOptionsFactory,
|
||||
} from "../../dal"
|
||||
import { mikroOrmCreateConnection } from "../../dal"
|
||||
import { isSharedConnectionSymbol } from "../create-pg-connection"
|
||||
import { loadDatabaseConfig } from "../load-module-database-config"
|
||||
|
||||
@@ -39,9 +35,6 @@ export async function mikroOrmConnectionLoader({
|
||||
logger?: Logger
|
||||
pathToMigrations: string
|
||||
}) {
|
||||
const freeTextSearchGlobalFilter =
|
||||
mikroOrmFreeTextSearchFilterOptionsFactory(entities)
|
||||
|
||||
let manager = (
|
||||
options as ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
|
||||
)?.manager
|
||||
@@ -68,9 +61,6 @@ export async function mikroOrmConnectionLoader({
|
||||
return await loadShared({
|
||||
database: {
|
||||
...dbConfig,
|
||||
filters: {
|
||||
[FreeTextSearchFilterKey as string]: freeTextSearchGlobalFilter,
|
||||
},
|
||||
},
|
||||
container,
|
||||
entities,
|
||||
@@ -98,9 +88,6 @@ export async function mikroOrmConnectionLoader({
|
||||
manager ??= await loadDefault({
|
||||
database: {
|
||||
...dbConfig,
|
||||
filters: {
|
||||
[FreeTextSearchFilterKey as string]: freeTextSearchGlobalFilter,
|
||||
},
|
||||
},
|
||||
entities,
|
||||
pathToMigrations,
|
||||
|
||||
@@ -2,9 +2,9 @@ import {
|
||||
BaseFilterable,
|
||||
Context,
|
||||
FilterQuery,
|
||||
FilterQuery as InternalFilterQuery,
|
||||
FindConfig,
|
||||
InferEntityType,
|
||||
FilterQuery as InternalFilterQuery,
|
||||
ModulesSdkTypes,
|
||||
PerformedActions,
|
||||
UpsertWithReplaceConfig,
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
lowerCaseFirst,
|
||||
MedusaError,
|
||||
} from "../common"
|
||||
import { FreeTextSearchFilterKey } from "../dal"
|
||||
import { FreeTextSearchFilterKeyPrefix } from "../dal"
|
||||
import { DmlEntity, toMikroORMEntity } from "../dml"
|
||||
import { buildQuery } from "./build-query"
|
||||
import {
|
||||
@@ -67,7 +67,7 @@ export function MedusaInternalService<
|
||||
): void {
|
||||
if (isDefined(filters?.q)) {
|
||||
config.filters ??= {}
|
||||
config.filters[FreeTextSearchFilterKey] = {
|
||||
config.filters[FreeTextSearchFilterKeyPrefix + model.name] = {
|
||||
value: filters.q,
|
||||
fromEntity: model.name,
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
EntitySchema,
|
||||
MikroORMOptions,
|
||||
} from "@mikro-orm/core"
|
||||
import { defineConfig } from "@mikro-orm/postgresql"
|
||||
import { kebabCase } from "../common"
|
||||
import { CustomTsMigrationGenerator } from "../dal"
|
||||
import { DmlEntity, toMikroOrmEntities } from "../dml"
|
||||
@@ -21,7 +22,6 @@ type Options = Partial<Omit<MikroORMOptions, "entities" | "entitiesTs">> & {
|
||||
|
||||
type ReturnedOptions = Partial<MikroORMOptions> & {
|
||||
entities: MikroORMOptions["entities"]
|
||||
type: MikroORMOptions["type"]
|
||||
migrations: MikroORMOptions["migrations"]
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ export function defineMikroOrmCliConfig(
|
||||
|
||||
const dmlEntities = options.entities.filter(DmlEntity.isDmlEntity)
|
||||
const nonDmlEntities = options.entities.filter(
|
||||
(entity) => !DmlEntity.isDmlEntity(entity)
|
||||
(entity) => entity && !DmlEntity.isDmlEntity(entity)
|
||||
)
|
||||
|
||||
const entities = nonDmlEntities.concat(
|
||||
@@ -53,17 +53,16 @@ export function defineMikroOrmCliConfig(
|
||||
const normalizedModuleName = kebabCase(moduleName.replace("Service", ""))
|
||||
const databaseName = `medusa-${normalizedModuleName}`
|
||||
|
||||
return {
|
||||
type: "postgresql",
|
||||
return defineConfig({
|
||||
dbName: databaseName,
|
||||
host: "127.0.0.1",
|
||||
user: "postgres",
|
||||
password: "",
|
||||
...options,
|
||||
...(options as any),
|
||||
entities,
|
||||
migrations: {
|
||||
generator: CustomTsMigrationGenerator,
|
||||
...options.migrations,
|
||||
},
|
||||
}
|
||||
}) as ReturnedOptions
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user