feat(prduct, utils, types): Create soft delete pattern for link module (#4649)

* feat(prouct, utils, types): Create soft delete pattern for link module

* add comment

* add comment

* finalise

* remove linkable keys

* cleanup and tests

* cleanup

* add some comments and renaming

* re work

* fix tests

---------

Co-authored-by: Riqwan Thamir <rmthamir@gmail.com>
This commit is contained in:
Adrien de Peretti
2023-08-02 19:29:01 +02:00
committed by GitHub
co-authored by Riqwan Thamir
parent fc6c9df035
commit ce3326c5fb
17 changed files with 448 additions and 166 deletions
@@ -0,0 +1,43 @@
import { mapObjectTo, MapToConfig } from "../map-object-to"
const input = {
a: [{ id: "1" }, { id: "2" }],
b: [{ id: "3" }, { id: "4", handle: "handle1" }],
c: [{ id: "5", sku: "sku1" }, { id: "6" }],
}
const mapToConfig: MapToConfig = {
a: [{ mapTo: "a.id", valueFrom: "id" }],
b: [
{ mapTo: "b.id", valueFrom: "id" },
{ mapTo: "b.handle", valueFrom: "handle" },
],
c: [
{ mapTo: "c.id", valueFrom: "id" },
{ mapTo: "c.sku", valueFrom: "sku" },
],
}
describe("mapObjectTo", function () {
it("should return a new object with the keys remapped and the values picked from the original object based on the map config", function () {
const remappedObject = mapObjectTo(input, mapToConfig)
expect(remappedObject).toEqual({
"a.id": ["1", "2"],
"b.id": ["3", "4"],
"b.handle": ["handle1"],
"c.id": ["5", "6"],
"c.sku": ["sku1"],
})
})
it("should return a new object with only the picked properties", function () {
const remappedObject = mapObjectTo(input, mapToConfig, {
pick: ["a.id"],
})
expect(remappedObject).toEqual({
"a.id": ["1", "2"],
})
})
})
+1
View File
@@ -22,3 +22,4 @@ export * from "./stringify-circular"
export * from "./to-kebab-case"
export * from "./to-pascal-case"
export * from "./wrap-handler"
export * from "./map-object-to"
@@ -0,0 +1,53 @@
type RemapInputObject = Record<string, unknown[]>
type RemapConfig = { mapTo: string; valueFrom: string }
export type MapToConfig = {
[key: string]: RemapConfig[]
}
/**
* Create a new object with the keys remapped and the values picked from the original object based
* on the map config
*
* @param object input object
* @param mapTo configuration to map the output object
* @param removeIfNotRemapped if true, the keys that are not remapped will be removed from the output object
* @param pick if provided, only the keys in the array will be picked from the output object
*/
export function mapObjectTo<
TResult = any,
T extends RemapInputObject = RemapInputObject
>(
object: T,
mapTo: MapToConfig,
{
removeIfNotRemapped,
pick,
}: { removeIfNotRemapped?: boolean; pick?: string[] } = {}
): TResult {
removeIfNotRemapped ??= false
const newObject: Record<string, any> = {}
for (const key in object) {
const remapConfig = mapTo[key as string]!
if (!remapConfig) {
if (!removeIfNotRemapped) {
newObject[key] = object[key]
}
continue
}
remapConfig.forEach((config) => {
if (pick?.length && !pick.includes(config.mapTo)) {
return
}
newObject[config.mapTo] = object[key]
.map((obj: any) => obj[config.valueFrom])
.filter(Boolean)
})
}
return newObject as TResult
}
+1
View File
@@ -1,5 +1,6 @@
export * from "./mikro-orm/mikro-orm-repository"
export * from "./repository"
export * from "./utils"
export * from "./mikro-orm/utils"
export * from "./mikro-orm/mikro-orm-create-connection"
export * from "./mikro-orm/mikro-orm-soft-deletable-filter"
@@ -2,10 +2,10 @@ import { Context, DAL, RepositoryTransformOptions } from "@medusajs/types"
import { MedusaContext } from "../../decorators"
import { buildQuery, InjectTransactionManager } from "../../modules-sdk"
import {
mikroOrmSerializer,
mikroOrmUpdateDeletedAtRecursively,
getSoftDeletedCascadedEntitiesIdsMappedBy,
transactionWrapper,
} from "../utils"
import { mikroOrmSerializer, mikroOrmUpdateDeletedAtRecursively } from "./utils"
class MikroOrmBase<T = any> {
protected readonly manager_: any
@@ -71,13 +71,17 @@ export abstract class MikroOrmAbstractBaseRepository<T = any>
ids: string[],
@MedusaContext()
{ transactionManager: manager }: Context = {}
): Promise<T[]> {
): Promise<[T[], Record<string, unknown[]>]> {
const entities = await this.find({ where: { id: { $in: ids } } as any })
const date = new Date()
await mikroOrmUpdateDeletedAtRecursively(manager, entities, date)
return entities
const softDeletedEntitiesMap = getSoftDeletedCascadedEntitiesIdsMappedBy({
entities,
})
return [entities, softDeletedEntitiesMap]
}
@InjectTransactionManager()
+54
View File
@@ -0,0 +1,54 @@
import { SoftDeletableFilterKey } from "./mikro-orm-soft-deletable-filter"
export const mikroOrmUpdateDeletedAtRecursively = async <
T extends object = any
>(
manager: any,
entities: (T & { id: string; deleted_at?: string | Date | null })[],
value: Date | null
) => {
for (const entity of entities) {
if (!("deleted_at" in entity)) continue
entity.deleted_at = value
const relations = manager
.getDriver()
.getMetadata()
.get(entity.constructor.name).relations
const relationsToCascade = relations.filter((relation) =>
relation.cascade.includes("soft-remove" as any)
)
for (const relation of relationsToCascade) {
let collectionRelation = entity[relation.name]
if (!collectionRelation.isInitialized()) {
await collectionRelation.init()
}
const relationEntities = await collectionRelation.getItems({
filters: {
[SoftDeletableFilterKey]: {
withDeleted: true,
},
},
})
await mikroOrmUpdateDeletedAtRecursively(manager, relationEntities, value)
}
await manager.persist(entity)
}
}
export const mikroOrmSerializer = async <TOutput extends object>(
data: any,
options?: any
): Promise<TOutput> => {
options ??= {}
const { serialize } = await import("@mikro-orm/core")
const result = serialize(data, options)
return result as unknown as Promise<TOutput>
}
+4 -1
View File
@@ -49,7 +49,10 @@ export abstract class AbstractBaseRepository<T = any>
abstract delete(ids: string[], context?: Context): Promise<void>
abstract softDelete(ids: string[], context?: Context): Promise<T[]>
abstract softDelete(
ids: string[],
context?: Context
): Promise<[T[], Record<string, unknown[]>]>
abstract restore(ids: string[], context?: Context): Promise<T[]>
+44 -46
View File
@@ -1,4 +1,4 @@
import { SoftDeletableFilterKey } from "../dal"
import { isObject } from "../common"
export async function transactionWrapper<TManager = unknown>(
this: any,
@@ -33,54 +33,52 @@ export async function transactionWrapper<TManager = unknown>(
return await transactionMethod.bind(this.manager_)(task, options)
}
export const mikroOrmUpdateDeletedAtRecursively = async <
T extends object = any
>(
manager: any,
entities: T[],
value: Date | null
) => {
/**
* Can be used to create a new Object that collect the entities
* based on the columnLookup. This is useful when you want to soft delete entities and return
* an object where the keys are the entities name and the values are the entities
* that were soft deleted.
*
* @param entities
* @param deletedEntitiesMap
* @param getEntityName
*/
export function getSoftDeletedCascadedEntitiesIdsMappedBy({
entities,
deletedEntitiesMap,
getEntityName,
}: {
entities: any[]
deletedEntitiesMap?: Map<string, any[]>
getEntityName?: (entity: any) => string
}): Record<string, any[]> {
deletedEntitiesMap ??= new Map<string, any[]>()
getEntityName ??= (entity) => entity.constructor.name
for (const entity of entities) {
if (!("deleted_at" in entity)) continue
;(entity as any).deleted_at = value
const entityName = getEntityName(entity)
const shouldSkip = !!deletedEntitiesMap
.get(entityName)
?.some((e) => e.id === entity.id)
const relations = manager
.getDriver()
.getMetadata()
.get(entity.constructor.name).relations
const relationsToCascade = relations.filter((relation) =>
relation.cascade.includes("soft-remove" as any)
)
for (const relation of relationsToCascade) {
let collectionRelation = entity[relation.name]
if (!collectionRelation.isInitialized()) {
await collectionRelation.init()
}
const relationEntities = await collectionRelation.getItems({
filters: {
[SoftDeletableFilterKey]: {
withDeleted: true,
},
},
})
await mikroOrmUpdateDeletedAtRecursively(manager, relationEntities, value)
if (!entity.deleted_at || shouldSkip) {
continue
}
await manager.persist(entity)
}
}
const values = deletedEntitiesMap.get(entityName) ?? []
values.push(entity)
deletedEntitiesMap.set(entityName, values)
export const mikroOrmSerializer = async <TOutput extends object>(
data: any,
options?: any
): Promise<TOutput> => {
options ??= {}
const { serialize } = await import("@mikro-orm/core")
const result = serialize(data, options)
return result as unknown as Promise<TOutput>
Object.values(entity).forEach((propValue: any) => {
if (propValue != null && isObject(propValue[0])) {
getSoftDeletedCascadedEntitiesIdsMappedBy({
entities: propValue,
deletedEntitiesMap,
getEntityName,
})
}
})
}
return Object.fromEntries(deletedEntitiesMap)
}