chore(): Remove default limit from the build query (#9257)

* chore(): Remove default limit from the build query

* rm take: null

* fix tests

* fix tests

* fix db usage

* fix typo

* rm unsused template arg

* fixes

* fixes

* fixes

* fixes

* fixes

* fixes

* fixes
This commit is contained in:
Adrien de Peretti authored and GitHub committed 2024-09-24 16:06:45 +02:00
1 parent 9e711720dd
commit 90d530565b
41 files changed
+549 -224

No files matched your search

@@ -42,7 +42,7 @@ export const getPromotionCodesToApply = createStep(
(
await promotionService.listPromotions(
{ code: adjustmentCodes },
{ select: ["code"], take: null }
{ select: ["code"] }
)
).map((p) => p.code!)
)
@@ -31,7 +31,6 @@ async function getCurrentShippingOptionPriceSetsLinks(
service: LINKS.ShippingOptionPriceSet,
variables: {
filters: { shipping_option_id: shippingOptionIds },
take: null,
},
fields: ["shipping_option_id", "price_set_id"],
} as any)) as {
@@ -36,7 +36,6 @@ async function getCurrentShippingOptionPrices(
service: LINKS.ShippingOptionPriceSet,
variables: {
filters: { shipping_option_id: shippingOptionIds },
take: null,
},
fields: ["shipping_option_id", "price_set_id", "price_set.prices.*"],
} as any)) as {
@@ -4,7 +4,7 @@ import {
MedusaError,
Modules,
} from "@medusajs/utils"
import { StepResponse, createStep } from "@medusajs/workflows-sdk"
import { createStep, StepResponse } from "@medusajs/workflows-sdk"
export type FulfillmentProviderValidationWorkflowInput = {
id?: string
@@ -36,7 +36,6 @@ export const validateFulfillmentProvidersStep = createStep(
},
{
select: ["id", "service_zone_id", "provider_id"],
take: null,
}
)
@@ -19,7 +19,7 @@ export const getExistingPriceListsPriceIdsStep = createStep(
const existingPrices = priceListIds.length
? await pricingModule.listPrices(
{ price_list_id: priceListIds },
{ relations: ["price_list"], take: null }
{ relations: ["price_list"] }
)
: []
@@ -27,7 +27,7 @@ export const validateVariantPriceLinksStep = createStep(
const links = await remoteQuery({
entryPoint: "product_variant_price_set",
fields: ["variant_id", "price_set_id"],
variables: { variant_id: variantIds, take: null },
variables: { variant_id: variantIds },
})
const variantPriceSetMap: Record<string, string> = {}
@@ -16,19 +16,16 @@ export const updatePricePreferencesAsArrayStep = createStep(
const service = container.resolve<IPricingModuleService>(Modules.PRICING)
const prevData = await service.listPricePreferences({
$or: input.map(
(entry) => {
if (!entry.attribute || !entry.value) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Attribute and value must be provided when updating price preferences"
)
}
$or: input.map((entry) => {
if (!entry.attribute || !entry.value) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Attribute and value must be provided when updating price preferences"
)
}
return { attribute: entry.attribute, value: entry.value }
},
{ take: null }
),
return { attribute: entry.attribute, value: entry.value }
}, {}),
})
const toUpsert = input.map((entry) => {
@@ -1,6 +1,6 @@
import { IProductModuleService, LinkWorkflowInput } from "@medusajs/types"
import { Modules } from "@medusajs/utils"
import { StepResponse, createStep } from "@medusajs/workflows-sdk"
import { createStep, StepResponse } from "@medusajs/workflows-sdk"
export const batchLinkProductsToCollectionStepId =
"batch-link-products-to-collection"
@@ -17,7 +17,6 @@ export const batchLinkProductsToCollectionStep = createStep(
}
const dbCollection = await service.retrieveProductCollection(data.id, {
take: null,
select: ["id", "products.id"],
relations: ["products"],
})
@@ -1,6 +1,6 @@
import { IProductModuleService, ProductCategoryWorkflow } from "@medusajs/types"
import { Modules } from "@medusajs/utils"
import { StepResponse, createStep } from "@medusajs/workflows-sdk"
import { createStep, StepResponse } from "@medusajs/workflows-sdk"
export const batchLinkProductsToCategoryStepId =
"batch-link-products-to-category"
@@ -23,7 +23,6 @@ export const batchLinkProductsToCategoryStep = createStep(
const dbProducts = await service.listProducts(
{ id: [...(data.add ?? []), ...(data.remove ?? [])] },
{
take: null,
select: ["id", "categories"],
}
)
@@ -63,7 +62,6 @@ export const batchLinkProductsToCategoryStep = createStep(
const dbProducts = await service.listProducts(
{ id: prevData.productIds },
{
take: null,
select: ["id", "categories"],
}
)
@@ -71,7 +71,7 @@ export const generateProductCsvStep = createStep(
const regions = await regionService.listRegions(
{},
{ select: ["id", "name", "currency_code"], take: null }
{ select: ["id", "name", "currency_code"] }
)
const normalizedData = normalizeForExport(products, { regions })
@@ -21,7 +21,7 @@ export const getProductsStep = createStep(
const products = await service.listProducts(
{ id: data.ids },
{ relations: ["variants"], take: null }
{ relations: ["variants"] }
)
return new StepResponse(products, products)
}
@@ -19,7 +19,7 @@ export const groupProductsForBatchStep = createStep(
// We use the ID to do product updates
id: data.map((product) => product.id).filter(Boolean) as string[],
},
{ take: null, select: ["handle"] }
{ select: ["handle"] }
)
const existingProductsSet = new Set(existingProducts.map((p) => p.id))
@@ -30,9 +30,9 @@ export const parseProductCsvStep = createStep(
const [productTypes, productCollections, salesChannels] = await Promise.all(
[
productService.listProductTypes({}, { take: null }),
productService.listProductCollections({}, { take: null }),
salesChannelService.listSalesChannels({}, { take: null }),
productService.listProductTypes({}, {}),
productService.listProductCollections({}, {}),
salesChannelService.listSalesChannels({}, {}),
]
)
@@ -55,12 +55,9 @@ export const parseProductCsvStep = createStep(
const [allRegions, allTags] = await Promise.all([
regionService.listRegions(
{},
{ select: ["id", "name", "currency_code"], take: null }
),
productService.listProductTags(
{},
{ select: ["id", "value"], take: null }
{ select: ["id", "name", "currency_code"] }
),
productService.listProductTags({}, { select: ["id", "value"] }),
])
const normalizedData = normalizeForImport(v1Normalized, {
@@ -66,7 +66,6 @@ async function getCurrentRegionPaymentProvidersLinks(
service: LINKS.RegionPaymentProvider,
variables: {
filters: { region_id: regionIds },
take: null,
},
fields: ["region_id", "payment_provider_id"],
} as any)) as {
@@ -1,4 +1,15 @@
import { MikroORM, Options, SqlEntityManager } from "@mikro-orm/postgresql"
import { createDatabase, dropDatabase } from "pg-god"
const DB_HOST = process.env.DB_HOST ?? "localhost"
const DB_USERNAME = process.env.DB_USERNAME ?? ""
const DB_PASSWORD = process.env.DB_PASSWORD ?? ""
const pgGodCredentials = {
user: DB_USERNAME,
password: DB_PASSWORD,
host: DB_HOST,
}
export function getDatabaseURL(dbName?: string): string {
const DB_HOST = process.env.DB_HOST ?? "localhost"
@@ -158,3 +169,46 @@ export function getMikroOrmWrapper({
},
}
}
export const dbTestUtilFactory = (): any => ({
pgConnection_: null,
create: async function (dbName: string) {
await createDatabase(
{ databaseName: dbName, errorIfExist: false },
pgGodCredentials
)
},
teardown: async function ({ schema }: { schema?: string } = {}) {
if (!this.pgConnection_) {
return
}
const runRawQuery = this.pgConnection_.raw.bind(this.pgConnection_)
schema ??= "public"
await runRawQuery(`SET session_replication_role = 'replica';`)
const { rows: tableNames } = await runRawQuery(`SELECT table_name
FROM information_schema.tables
WHERE table_schema = '${schema}';`)
for (const { table_name } of tableNames) {
await runRawQuery(`DELETE
FROM ${schema}."${table_name}";`)
}
await runRawQuery(`SET session_replication_role = 'origin';`)
},
shutdown: async function (dbName: string) {
await this.pgConnection_?.context?.destroy()
await this.pgConnection_?.destroy()
return await dropDatabase(
{ databaseName: dbName, errorIfNonExist: false },
pgGodCredentials
)
},
})
@@ -4,5 +4,6 @@ export { default as IdMap } from "./id-map"
export * from "./init-modules"
export * as JestUtils from "./jest"
export * from "./medusa-test-runner"
export * from "./medusa-test-runner-utils/"
export { default as MockEventBusService } from "./mock-event-bus-service"
export * from "./module-test-runner"
@@ -0,0 +1,5 @@
export * from "./bootstrap-app"
export * from "./clear-instances"
export * from "./config"
export * from "./use-db"
export * from "./utils"
@@ -5,8 +5,7 @@ import {
createMedusaContainer,
} from "@medusajs/utils"
import { asValue } from "awilix"
import { createDatabase, dropDatabase } from "pg-god"
import { getDatabaseURL } from "./database"
import { dbTestUtilFactory, getDatabaseURL } from "./database"
import { startApp } from "./medusa-test-runner-utils/bootstrap-app"
import { clearInstances } from "./medusa-test-runner-utils/clear-instances"
import { configLoaderOverride } from "./medusa-test-runner-utils/config"
@@ -17,60 +16,7 @@ import {
} from "./medusa-test-runner-utils/use-db"
import { applyEnvVarsToProcess } from "./medusa-test-runner-utils/utils"
const DB_HOST = process.env.DB_HOST
const DB_USERNAME = process.env.DB_USERNAME ?? ""
const DB_PASSWORD = process.env.DB_PASSWORD ?? ""
const pgGodCredentials = {
user: DB_USERNAME,
password: DB_PASSWORD,
host: DB_HOST,
}
export const dbTestUtilFactory = (): any => ({
pgConnection_: null,
create: async function (dbName: string) {
await createDatabase(
{ databaseName: dbName, errorIfExist: false },
pgGodCredentials
)
},
teardown: async function ({ schema }: { schema?: string } = {}) {
if (!this.pgConnection_) {
return
}
const runRawQuery = this.pgConnection_.raw.bind(this.pgConnection_)
schema ??= "public"
await runRawQuery(`SET session_replication_role = 'replica';`)
const { rows: tableNames } = await runRawQuery(`SELECT table_name
FROM information_schema.tables
WHERE table_schema = '${schema}';`)
for (const { table_name } of tableNames) {
await runRawQuery(`DELETE
FROM ${schema}."${table_name}";`)
}
await runRawQuery(`SET session_replication_role = 'origin';`)
},
shutdown: async function (dbName: string) {
await this.pgConnection_?.context?.destroy()
await this.pgConnection_?.destroy()
return await dropDatabase(
{ databaseName: dbName, errorIfNonExist: false },
pgGodCredentials
)
},
})
export interface MedusaSuiteOptions<TService = unknown> {
export interface MedusaSuiteOptions {
dbConnection: any // knex instance
getContainer: () => MedusaContainer
api: any
@@ -106,7 +52,7 @@ export function medusaIntegrationTestRunner({
schema?: string
debug?: boolean
inApp?: boolean
testSuite: <TService = unknown>(options: MedusaSuiteOptions<TService>) => void
testSuite: (options: MedusaSuiteOptions) => void
}) {
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
moduleName = moduleName ?? Math.random().toString(36).substring(7)
@@ -20,7 +20,7 @@ class RecursiveEntity1 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@OneToMany(() => RecursiveEntity2, (entity2) => entity2.entity1, {
@@ -44,7 +44,7 @@ class RecursiveEntity2 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => RecursiveEntity1, {
@@ -64,7 +64,7 @@ class Entity1 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@OneToMany(() => Entity2, (entity2) => entity2.entity1, {
@@ -89,7 +89,7 @@ class Entity2 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => Entity1, { mapToPk: true })
@@ -111,7 +111,7 @@ class DeepRecursiveEntity1 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@OneToMany(() => DeepRecursiveEntity2, (entity2) => entity2.entity1, {
@@ -136,7 +136,7 @@ class DeepRecursiveEntity2 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => DeepRecursiveEntity1)
@@ -163,7 +163,7 @@ class DeepRecursiveEntity3 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => DeepRecursiveEntity1, {
@@ -187,7 +187,7 @@ class DeepRecursiveEntity4 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => DeepRecursiveEntity1)
@@ -214,7 +214,7 @@ class InternalCircularDependencyEntity1 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@OneToMany(
@@ -226,7 +226,7 @@ class InternalCircularDependencyEntity1 {
)
children = new Collection<InternalCircularDependencyEntity1>(this)
@ManyToOne(() => InternalCircularDependencyEntity1)
@ManyToOne(() => InternalCircularDependencyEntity1, { nullable: true })
parent: Rel<InternalCircularDependencyEntity1>
}
@@ -244,7 +244,7 @@ class Entity1WithUnDecoratedProp {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@OneToMany(() => Entity2WithUnDecoratedProp, (entity2) => entity2.entity1, {
@@ -271,7 +271,7 @@ class Entity2WithUnDecoratedProp {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => Entity1WithUnDecoratedProp, { mapToPk: true })
@@ -293,7 +293,7 @@ class SearchableEntity1 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@Searchable()
@@ -321,7 +321,7 @@ class SearchableEntity2 {
@PrimaryKey()
id: string
@Property()
@Property({ nullable: true })
deleted_at: Date | null
@Searchable()
@@ -0,0 +1,15 @@
const DB_HOST = process.env.DB_HOST ?? "localhost"
const DB_USERNAME = process.env.DB_USERNAME ?? ""
const DB_PASSWORD = process.env.DB_PASSWORD
export const pgGodCredentials = {
user: DB_USERNAME,
password: DB_PASSWORD,
host: DB_HOST,
}
export function getDatabaseURL(dbName): string {
return `postgres://${DB_USERNAME}${
DB_PASSWORD ? `:${DB_PASSWORD}` : ""
}@${DB_HOST}/${dbName}`
}
@@ -0,0 +1,352 @@
import {
Collection,
Entity,
ManyToOne,
OneToMany,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"
import { Searchable } from "../../decorators/searchable"
// Circular dependency one level
@Entity()
class RecursiveEntity1 {
constructor(props: { id: string; deleted_at: Date | null }) {
this.id = props.id
this.deleted_at = props.deleted_at
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@OneToMany(() => RecursiveEntity2, (entity2) => entity2.entity1, {
cascade: ["soft-remove"] as any,
})
entity2 = new Collection<RecursiveEntity2>(this)
}
@Entity()
class RecursiveEntity2 {
constructor(props: {
id: string
deleted_at: Date | null
entity1: RecursiveEntity1
}) {
this.id = props.id
this.deleted_at = props.deleted_at
this.entity1 = props.entity1
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => RecursiveEntity1, {
cascade: ["soft-remove"] as any,
})
entity1: Rel<RecursiveEntity1>
}
// No circular dependency
@Entity()
class Entity1 {
constructor(props: { id: string; deleted_at: Date | null }) {
this.id = props.id
this.deleted_at = props.deleted_at
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@OneToMany(() => Entity2, (entity2) => entity2.entity1, {
cascade: ["soft-remove"] as any,
})
entity2 = new Collection<Entity2>(this)
}
@Entity()
class Entity2 {
constructor(props: {
id: string
deleted_at: Date | null
entity1: Rel<Entity1>
}) {
this.id = props.id
this.deleted_at = props.deleted_at
this.entity1 = props.entity1
this.entity1_id = props.entity1.id
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => Entity1, { mapToPk: true })
entity1_id: string
@ManyToOne(() => Entity1, { persist: false })
entity1: Entity1
}
// Circular dependency deep level
@Entity()
class DeepRecursiveEntity1 {
constructor(props: { id: string; deleted_at: Date | null }) {
this.id = props.id
this.deleted_at = props.deleted_at
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@OneToMany(() => DeepRecursiveEntity2, (entity2) => entity2.entity1, {
cascade: ["soft-remove"] as any,
})
entity2 = new Collection<DeepRecursiveEntity2>(this)
}
@Entity()
class DeepRecursiveEntity2 {
constructor(props: {
id: string
deleted_at: Date | null
entity1: Rel<DeepRecursiveEntity1>
entity3: Rel<DeepRecursiveEntity3>
}) {
this.id = props.id
this.deleted_at = props.deleted_at
this.entity3 = props.entity3
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => DeepRecursiveEntity1)
entity1: DeepRecursiveEntity1
@ManyToOne(() => DeepRecursiveEntity3, {
cascade: ["soft-remove"] as any,
})
entity3: Rel<DeepRecursiveEntity3>
}
@Entity()
class DeepRecursiveEntity3 {
constructor(props: {
id: string
deleted_at: Date | null
entity1: Rel<DeepRecursiveEntity1>
}) {
this.id = props.id
this.deleted_at = props.deleted_at
this.entity1 = props.entity1
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => DeepRecursiveEntity1, {
cascade: ["soft-remove"] as any,
})
entity1: Rel<DeepRecursiveEntity1>
}
@Entity()
class DeepRecursiveEntity4 {
constructor(props: {
id: string
deleted_at: Date | null
entity1: Rel<DeepRecursiveEntity1>
}) {
this.id = props.id
this.deleted_at = props.deleted_at
this.entity1 = props.entity1
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => DeepRecursiveEntity1)
entity1: Rel<DeepRecursiveEntity1>
}
// Internal circular dependency
@Entity()
class InternalCircularDependencyEntity1 {
constructor(props: {
id: string
deleted_at: Date | null
parent?: InternalCircularDependencyEntity1
}) {
this.id = props.id
this.deleted_at = props.deleted_at
if (props.parent) {
this.parent = props.parent
}
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@OneToMany(
() => InternalCircularDependencyEntity1,
(entity) => entity.parent,
{
cascade: ["soft-remove"] as any,
}
)
children = new Collection<InternalCircularDependencyEntity1>(this)
@ManyToOne(() => InternalCircularDependencyEntity1, { nullable: true })
parent: Rel<InternalCircularDependencyEntity1>
}
// With un decorated prop
@Entity()
class Entity1WithUnDecoratedProp {
constructor(props: { id: string; deleted_at: Date | null }) {
this.id = props.id
this.deleted_at = props.deleted_at
}
unknownProp: string
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@OneToMany(() => Entity2WithUnDecoratedProp, (entity2) => entity2.entity1, {
cascade: ["soft-remove"] as any,
})
entity2 = new Collection<Entity2WithUnDecoratedProp>(this)
}
@Entity()
class Entity2WithUnDecoratedProp {
constructor(props: {
id: string
deleted_at: Date | null
entity1: Rel<Entity1WithUnDecoratedProp>
}) {
this.id = props.id
this.deleted_at = props.deleted_at
this.entity1 = props.entity1
this.entity1_id = props.entity1.id
}
unknownProp: string
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@ManyToOne(() => Entity1WithUnDecoratedProp, { mapToPk: true })
entity1_id: string
@ManyToOne(() => Entity1WithUnDecoratedProp, { persist: false })
entity1: Rel<Entity1WithUnDecoratedProp>
}
// Searchable fields
@Entity()
class SearchableEntity1 {
constructor(props: { id: string; deleted_at: Date | null }) {
this.id = props.id
this.deleted_at = props.deleted_at
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@Searchable()
@Property()
searchableField: string
@Searchable()
@OneToMany(() => SearchableEntity2, (entity2) => entity2.entity1)
entity2 = new Collection<SearchableEntity2>(this)
}
@Entity()
class SearchableEntity2 {
constructor(props: {
id: string
deleted_at: Date | null
entity1: SearchableEntity1
}) {
this.id = props.id
this.deleted_at = props.deleted_at
this.entity1 = props.entity1
this.entity1_id = props.entity1.id
}
@PrimaryKey()
id: string
@Property({ nullable: true })
deleted_at: Date | null
@Searchable()
@Property()
searchableField: string
@ManyToOne(() => SearchableEntity1, { mapToPk: true })
entity1_id: string
@ManyToOne(() => SearchableEntity1, { persist: false })
entity1: Rel<SearchableEntity1>
}
export {
DeepRecursiveEntity1,
DeepRecursiveEntity2,
DeepRecursiveEntity3,
DeepRecursiveEntity4,
Entity1,
Entity1WithUnDecoratedProp,
Entity2,
Entity2WithUnDecoratedProp,
InternalCircularDependencyEntity1,
RecursiveEntity1,
RecursiveEntity2,
SearchableEntity1,
SearchableEntity2,
}
@@ -18,23 +18,9 @@ import { dropDatabase } from "pg-god"
import { MikroOrmBigNumberProperty } from "../../big-number-field"
import BigNumber from "bignumber.js"
import { BigNumberRawValue } from "@medusajs/types"
import { getDatabaseURL, pgGodCredentials } from "../__fixtures__/database"
const DB_HOST = process.env.DB_HOST ?? "localhost"
const DB_USERNAME = process.env.DB_USERNAME ?? ""
const DB_PASSWORD = process.env.DB_PASSWORD
const DB_NAME = "mikroorm-integration-1"
const pgGodCredentials = {
user: DB_USERNAME,
password: DB_PASSWORD,
host: DB_HOST,
}
export function getDatabaseURL(): string {
return `postgres://${DB_USERNAME}${
DB_PASSWORD ? `:${DB_PASSWORD}` : ""
}@${DB_HOST}/${DB_NAME}`
}
const dbName = "mikroorm-integration-1"
jest.setTimeout(300000)
@Entity()
@@ -153,13 +139,13 @@ describe("mikroOrmRepository", () => {
beforeEach(async () => {
await dropDatabase(
{ databaseName: DB_NAME, errorIfNonExist: false },
{ databaseName: dbName, errorIfNonExist: false },
pgGodCredentials
)
orm = await MikroORM.init({
entities: [Entity1, Entity2],
clientUrl: getDatabaseURL(),
clientUrl: getDatabaseURL(dbName),
type: "postgresql",
})
@@ -1,4 +1,4 @@
import { mikroOrmUpdateDeletedAtRecursively } from "../utils"
import { mikroOrmUpdateDeletedAtRecursively } from "../../utils"
import { MikroORM } from "@mikro-orm/core"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import {
@@ -12,6 +12,10 @@ import {
RecursiveEntity1,
RecursiveEntity2,
} from "../__fixtures__/utils"
import { dropDatabase } from "pg-god"
import { getDatabaseURL, pgGodCredentials } from "../__fixtures__/database"
const dbName = "mikroorm-utils-integration-1"
jest.mock("@mikro-orm/core", () => ({
...jest.requireActual("@mikro-orm/core"),
@@ -29,6 +33,11 @@ describe("mikroOrmUpdateDeletedAtRecursively", () => {
let orm!: MikroORM
beforeEach(async () => {
await dropDatabase(
{ databaseName: dbName, errorIfNonExist: false },
pgGodCredentials
)
orm = await MikroORM.init({
entities: [
Entity1,
@@ -41,13 +50,19 @@ describe("mikroOrmUpdateDeletedAtRecursively", () => {
DeepRecursiveEntity4,
InternalCircularDependencyEntity1,
],
dbName: "test",
clientUrl: getDatabaseURL(dbName),
type: "postgresql",
})
const generator = orm.getSchemaGenerator()
await generator.ensureDatabase()
await generator.createSchema()
})
afterEach(async () => {
await orm.close()
const generator = orm.getSchemaGenerator()
await generator.dropSchema()
await orm.close(true)
})
it("should successfully mark the entities deleted_at recursively", async () => {
@@ -59,12 +74,14 @@ describe("mikroOrmUpdateDeletedAtRecursively", () => {
entity1: entity1,
})
entity1.entity2.add(entity2)
manager.persist(entity1)
manager.persist(entity2)
const deletedAt = new Date()
await mikroOrmUpdateDeletedAtRecursively(manager, [entity1], deletedAt)
expect(entity1.deleted_at).toEqual(deletedAt)
expect(entity2.deleted_at).toEqual(deletedAt)
expect(!!entity1.deleted_at).toEqual(true)
expect(!!entity2.deleted_at).toEqual(true)
})
it("should successfully mark the entities deleted_at recursively with internal parent/child relation", async () => {
@@ -80,11 +97,14 @@ describe("mikroOrmUpdateDeletedAtRecursively", () => {
parent: entity1,
})
manager.persist(entity1)
manager.persist(childEntity1)
const deletedAt = new Date()
await mikroOrmUpdateDeletedAtRecursively(manager, [entity1], deletedAt)
expect(entity1.deleted_at).toEqual(deletedAt)
expect(childEntity1.deleted_at).toEqual(deletedAt)
expect(!!entity1.deleted_at).toEqual(true)
expect(!!childEntity1.deleted_at).toEqual(true)
})
it("should throw an error when a circular dependency is detected", async () => {
+11 -10
View File
@@ -1,4 +1,4 @@
import { EntityMetadata, FindOptions, wrap } from "@mikro-orm/core"
import { Collection, EntityMetadata, FindOptions, wrap } from "@mikro-orm/core"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { buildQuery } from "../../modules-sdk/build-query"
@@ -92,28 +92,29 @@ async function performCascadingSoftDeletion<T>(
)
}
entityRelation = await retrieveEntity()
entityRelation = entityRelation[relation.name]
if (!entityRelation) {
// Fixes the case of many to many through pivot table
entityRelation = await retrieveEntity()
if (!entityRelation) {
continue
}
continue
}
const isCollection = "toArray" in entityRelation
let relationEntities: any[] = []
if (isCollection) {
if (!entityRelation.isInitialized()) {
if (!(entityRelation as Collection<any, any>).isInitialized()) {
entityRelation = await retrieveEntity()
entityRelation = entityRelation[relation.name]
}
relationEntities = entityRelation.getItems()
} else {
const wrappedEntity = wrap(entityRelation)
const initializedEntityRelation = wrappedEntity.isInitialized()
? entityRelation
: await wrap(entityRelation).init()
let initializedEntityRelation = entityRelation
if (!wrappedEntity.isInitialized()) {
initializedEntityRelation = await wrap(entityRelation).init()
}
relationEntities = [initializedEntityRelation]
}
@@ -1,5 +1,5 @@
import { DAL, FindConfig } from "@medusajs/types"
import { deduplicate, isDefined, isObject } from "../common"
import { deduplicate, isObject } from "../common"
import { SoftDeletableFilterKey } from "../dal/mikro-orm/mikro-orm-soft-deletable-filter"
@@ -18,33 +18,13 @@ export function buildQuery<T = any, TDto = any>(
const filterFlags: FilterFlags = {}
buildWhere(filters, where, filterFlags)
const primaryKeyFieldArray = isDefined(config.primaryKeyFields)
? !Array.isArray(config.primaryKeyFields)
? [config.primaryKeyFields]
: config.primaryKeyFields
: ["id"]
const whereHasPrimaryKeyFields = primaryKeyFieldArray.some(
(pkField) => !!where[pkField]
)
const defaultLimit = whereHasPrimaryKeyFields ? undefined : 15
delete config.primaryKeyFields
const findOptions: DAL.OptionsQuery<T, any> = {
populate: deduplicate(config.relations ?? []),
fields: config.select as string[],
limit:
(Number.isSafeInteger(config.take) && config.take! >= 0) ||
null === config.take
? config.take ?? undefined
: defaultLimit,
offset:
(Number.isSafeInteger(config.skip) && config.skip! >= 0) ||
null === config.skip
? config.skip ?? undefined
: 0,
limit: (Number.isSafeInteger(config.take) && config.take) || undefined,
offset: (Number.isSafeInteger(config.skip) && config.skip) || undefined,
}
if (config.order) {
@@ -272,9 +272,7 @@ export function MedusaInternalService<
if (input_.selector) {
const entitiesToUpdate = await this.list(
input_.selector,
{
take: null,
},
{},
sharedContext
)
// Create a pair of entity and data to update
@@ -303,7 +301,7 @@ export function MedusaInternalService<
if (keySelectorForDataOnly.$or.length) {
const entitiesToUpdate = await this.list(
keySelectorForDataOnly,
{ take: null },
{},
sharedContext
)