UNPKG

typeorm-erd

Version:

Create ERD from TypeORM with outputs as Mermaid, or PlantUML

78 lines (77 loc) 2.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PlantUMLErd = 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 plantuml string based on the specification here: * https://plantuml.com/ie-diagram */ class PlantUMLErd { 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 `@startuml\nskinparam linetype ortho\n${this.renderTables()}\n${this.renderRelations()}\n@enduml`; } 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}`; }); return [...acc, ...relations.filter(Boolean)]; }, []); } renderTables() { return this.meta .map((entry) => { const columns = entry.columns.map((column) => { const { databaseName, isPrimary, referencedColumn, comment, length } = column; const normalizedColumnName = this.dataSource.driver .normalizeType(column) .toUpperCase(); const columnName = length ? `${normalizedColumnName}(${length})` : normalizedColumnName; return [ databaseName, columnName, isPrimary ? "<<PK>>" : referencedColumn ? "<<FK>>" : "", comment && `//"${comment}"//`, ] .filter(Boolean) .join(" : "); }); return `entity "${entry.tableName}" {\n ${columns.join("\n --\n ")}\n}`; }) .join("\n"); } } exports.PlantUMLErd = PlantUMLErd;