UNPKG

@mvx/typeorm-adapter

Version:

@mvx/typeorm-adapter is typeorm adapter orm for mvc, type-mvc is base on koa. Decorator, Ioc, AOP mvc frameworker on server.

89 lines (87 loc) 3.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); require("reflect-metadata"); const typeorm_1 = require("typeorm"); const ioc_1 = require("@tsdi/ioc"); const mvc_1 = require("@mvx/mvc"); let OrmInitService = class OrmInitService { static getClassAnnations() { return { "name": "OrmInitService", "params": { "init": ["connect"] } }; } }; OrmInitService = tslib_1.__decorate([ ioc_1.Abstract() ], OrmInitService); exports.OrmInitService = OrmInitService; let TypeOrmHelper = class TypeOrmHelper { constructor(ctx) { this.ctx = ctx; this.hasInit = false; } async getRepository(type) { let conn = await this.getConnection(); return conn.getRepository(type); } async getMongoRepository(type) { let conn = await this.getConnection(); return conn.getMongoRepository(type); } async getConnection() { let options = await this.getOptions(); if (!this.hasInit) { this.hasInit = true; try { let connect = await typeorm_1.createConnection(options); if (options.initDb) { await options.initDb(connect); } let initService = this.ctx.getService(OrmInitService); if (initService instanceof OrmInitService) { await initService.init(connect); } return connect; } catch (err) { console.error(err); } } return await typeorm_1.getConnection(options.name); } async getOptions() { if (!this.options) { let config = this.ctx.getConfiguration(); let options = config.connections || {}; if (!options.entities) { let entities = []; let loader = this.ctx.getContainer().getLoader(); if (config.models.some(m => ioc_1.isString(m))) { let models = await loader.loadTypes({ files: config.models, basePath: this.ctx.getRootPath() }); models.forEach(ms => { ms.forEach(mdl => { if (mdl && entities.indexOf(mdl) < 0) { entities.push(mdl); } }); }); } else { entities = config.models; } options.entities = entities; } this.options = options; } return this.options; } static getClassAnnations() { return { "name": "TypeOrmHelper", "params": { "constructor": ["ctx"], "getRepository": ["type"], "getMongoRepository": ["type"], "getConnection": [], "getOptions": [] } }; } }; TypeOrmHelper = tslib_1.__decorate([ ioc_1.Singleton, tslib_1.__param(0, ioc_1.Inject(mvc_1.MvcContextToken)), tslib_1.__metadata("design:paramtypes", [mvc_1.MvcContext]) ], TypeOrmHelper); exports.TypeOrmHelper = TypeOrmHelper; //# sourceMappingURL=sourcemaps/TypeOrmHelper.js.map