typeorm-erd
Version:
Create ERD from TypeORM with outputs as Mermaid, or PlantUML
71 lines (70 loc) • 2.56 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.MermaidErd = void 0;
const builder_1 = require("../builder");
const RelationShips = {
left: {
"one-to-many": "||",
"many-to-one": "}|",
"one-to-one": "||",
"many-to-many": "}|",
},
right: {
"one-to-many": "|{",
"many-to-one": "||",
"one-to-one": "||",
"many-to-many": "|{",
},
};
/**
* Render a mermaid ERD based on the spec here:
* https://mermaid-js.github.io/mermaid/#/entityRelationshipDiagram
*/
class MermaidErd {
constructor(dataSource, entityBuilder = builder_1.builders.entityMetaData, relationBuilder = builder_1.builders.relations) {
this.dataSource = dataSource;
this.entityBuilder = entityBuilder;
this.relationBuilder = relationBuilder;
this.dataSource = dataSource;
this.entityBuilder = entityBuilder;
}
async initialize() {
this.meta = await this.entityBuilder(this.dataSource);
this.relations = await this.relationBuilder(this.meta);
}
render() {
return `erDiagram\n ${this.renderTables()}\n ${this.renderRelations()}`;
}
renderRelations() {
return this.buildRelations().join("\n ");
}
buildRelations() {
return Object.entries(this.relations).reduce((acc, [key, values]) => {
const relations = values.entityRelations.map((rel) => {
// Remove unnamed relations and only add relations for the explicit owner
if (!rel.propertyPath || !rel.isOwning)
return "";
return `${rel.source} ${RelationShips["left"][rel.relationType]}--${RelationShips["right"][rel.relationType]} ${rel.target}: ${rel.propertyPath}`;
});
return [...acc, ...relations.filter(Boolean)];
}, []);
}
renderTables() {
return this.meta
.map((entry) => {
const columns = entry.columns.map((column) => {
return [
this.dataSource.driver.normalizeType(column),
column.databaseName,
column.isPrimary ? "PK" : column.referencedColumn ? "FK" : "",
column.comment && `"${column.comment}"`,
]
.filter(Boolean)
.join(" ");
});
return `${entry.tableName} {\n ${columns.join("\n ")}\n }`;
})
.join("\n ");
}
}
exports.MermaidErd = MermaidErd;
;