Last active
July 24, 2019 10:43
-
-
Save iteufel/fc84059d43fabbfe13bb65a132d17fc0 to your computer and use it in GitHub Desktop.
TypeOrm delete Nested
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { getManager } from 'typeorm'; | |
import * as dotProp from 'dot-prop'; | |
export async function deleteNested (item: any) { | |
const meta = getRemoveRelations(item.constructor, ''); | |
const res = await getManager().findOneOrFail(item.constructor, item, { | |
relations: meta | |
}) | |
await getManager().remove(res); | |
for (const path of meta) { | |
const prop = dotProp.get(res, path); | |
await getManager().remove(prop); | |
} | |
} | |
function getRemoveRelations (entity: any, path: string) { | |
let delData = []; | |
const meta = getManager().connection.getMetadata(entity) | |
for (const relation of meta.ownRelations) { | |
if (relation.isOneToOne) { | |
const cpath = [...(path.length > 0 ? [path] : []), relation.propertyPath].join('.'); | |
delData = [...delData, cpath, ...getRemoveRelations(relation.type, cpath)] | |
} | |
} | |
return delData; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment