import { AMProp } from "./types"; import { AmUtil } from "./util"; /** * 模型管理器 */ export class AMModelManager{ /** * model类map * key: model类名 * value: model类 */ public static modelMap:Map = new Map(); /** * 初始化模型 * @param paths 路径数组(model编译后的)或模型集 */ public static async init(paths:string[]|object){ if(typeof paths === 'object'){ for(let key of Object.keys(paths)){ //增加名称 paths[key].name = key; this.modelMap.set(key,paths[key]); } }else{ for(let path of paths){ await this.addModels(path); } } } /** * 添加model * @param cls model 类 */ public static addModel(cls:any){ this.modelMap.set(cls.name,cls); } /** * 获取model * @param clsName model类名 * @returns model类 */ public static getModel(clsName:string):any{ return this.modelMap.get(clsName); } /** * 获取model属性 * @param clsName model类名 * @param propName 属性名 * @returns 属性对象 */ public static getProp(clsName:string,propName:string):AMProp{ let props = this.modelMap.get(clsName).props; return props.find(item=>item.name === propName); } /** * 获取model id属性 * @param clsName model类名 * @returns id属性对象 */ public static getIdProp(clsName:string):AMProp{ let props = this.modelMap.get(clsName).props; return props.find(item=>item.isId); } /** * 从model添加实体到工厂 * @param path 文件路径 */ public static async addModels(path: string) { const basePath = process.cwd(); let pathArr = path.split('/'); let pa = [basePath]; let handled: boolean = false; //是否已处理 for (let i = 0; i < pathArr.length - 1; i++) { const p = pathArr[i]; if (p.indexOf('*') === -1 && p !== "") { pa.push(p); } else if (p === '**') { //所有子孙目录 handled = true; if (i < pathArr.length - 2) { throw "model init config is not correct!"; } await handleDir(pa.join('/'), pathArr[pathArr.length - 1], true); } } if (!handled) { await handleDir(pa.join('/'), pathArr[pathArr.length - 1]); } /** * 处理子目录 * @param dirPath 目录路径 * @param fileExt 文件扩展名 * @param deep 是否深度遍历 */ async function handleDir(dirPath: string, fileExt: string, deep?: boolean) { const fsMdl = require('fs'); const pathMdl = require('path'); const dir = fsMdl.readdirSync(dirPath, { withFileTypes: true }); let fn: string = fileExt; let reg: RegExp = AmUtil.toReg(fn,2); for (const dirent of dir) { if (dirent.isDirectory()) { if (deep) { await handleDir(pathMdl.resolve(dirPath, dirent.name), fileExt, deep); } } else if (dirent.isFile()) { if (reg.test(dirent.name)) { await import(pathMdl.resolve(dirPath, dirent.name)); } } } } } }