import { GET_INGER_DECORATOR, Injector, Type, Logger, Injectable } from '@notadd/core'; import { ColumnMetadataKey, ColumnOptions, EntityMetadataKey, EntityOptions } from '../decorators'; import { TYPEORM_NAMING_STRATEGY } from '../token'; import { DefaultNamingStrategy } from '../typeorm-native'; export type TEntityCache = { [key: string]: { title: string; columns: { [key: string]: string } } }; @Injectable() export class EntityColumnNameUtils { constructor(public injector: Injector) {} cache: TEntityCache = {}; getEntityColumnName(t: string, c: string): { table: string; column: string } { const table = this.cache[t]; let column = c; if (table && table.columns) { column = table.columns[c] || c; } return { table: table ? table.title || t : t, column: column, }; } saveEntityCache(entities: Type[]) { const logger = this.injector.get(Logger); const decorator = this.injector.get(GET_INGER_DECORATOR); const namingStrategy = this.injector.get(TYPEORM_NAMING_STRATEGY, new DefaultNamingStrategy()); entities.forEach((entity) => { const nger = decorator(entity); nger.classes.forEach((it) => { if (it.metadataKey === EntityMetadataKey) { const options = it.options as EntityOptions; if (options) { const table = { title: options.title, columns: {}, }; if (options.title && options.title.includes('_spare_')) { return; } nger.properties.forEach((it) => { if (it.metadataKey === ColumnMetadataKey) { const options = it.options as ColumnOptions; if (options) { Reflect.set(table.columns, options.name || it.property, options.comment); } } }); const defTableName = namingStrategy.tableName(it.type.name, undefined); Reflect.set( this.cache, options.name || namingStrategy.tableName(it.type.name, undefined), table ); logger.log(`${table.title || options.name || defTableName}表已准备好`); } } }); }); } }