UNPKG

@tsdi/typeorm-adapter

Version:

@tsdi/typeorm-adapter is typeorm adapter orm for boot application, mvc frameworks on server.

275 lines (267 loc) 10.4 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var tslib = require('tslib'); var ioc = require('@tsdi/ioc'); require('reflect-metadata'); var boot = require('@tsdi/boot'); var typeorm = require('typeorm'); exports.TypeormConnectionStatupService = class TypeormConnectionStatupService extends boot.ConnectionStatupService { /** * configure service. * @param ctx context. */ configureService(ctx) { var _a; return tslib.__awaiter(this, void 0, void 0, function* () { this.ctx = ctx; const logger = this.logger = (_a = ctx.getLogManager()) === null || _a === void 0 ? void 0 : _a.getLogger(); logger === null || logger === void 0 ? void 0 : logger.info('startup db connections'); const config = this.ctx.getConfiguration(); const injector = ctx.injector; if (config === null || config === void 0 ? void 0 : config.repositories.some(r => ioc.isString(r))) { let loader = this.ctx.injector.getLoader(); // preload repositories for typeorm. yield loader.loadTypes({ files: config.repositories.filter(r => ioc.isString(r)), basePath: this.ctx.baseURL }); } if (ioc.isArray(config.connections)) { yield Promise.all(config.connections.map((options) => this.statupConnection(injector, options, config))); } else if (config.connections) { let options = config.connections; options.asDefault = true; yield this.statupConnection(injector, options, config); } }); } statupConnection(injector, options, config) { var _a; return tslib.__awaiter(this, void 0, void 0, function* () { const connection = yield this.createConnection(options, config); if (options.initDb) { yield options.initDb(connection); } (_a = typeorm.getMetadataArgsStorage().entityRepositories) === null || _a === void 0 ? void 0 : _a.forEach(meta => { if (options.entities.indexOf(meta.entity) >= 0) { injector.set(meta.target, () => typeorm.getCustomRepository(meta.target, options.name)); } }); }); } /** * create connection. * @param options connenction options. * @param config config */ createConnection(options, config) { return tslib.__awaiter(this, void 0, void 0, function* () { if (options.asDefault && !options.entities) { let entities = []; if (config === null || config === void 0 ? void 0 : config.models.some(m => ioc.isString(m))) { let loader = this.ctx.injector.getLoader(); let models = yield loader.loadTypes({ files: config.models.filter(m => ioc.isString(m)), basePath: this.ctx.baseURL }); models.forEach(ms => { ms.forEach(mdl => { if (mdl && entities.indexOf(mdl) < 0) { entities.push(mdl); } }); }); } else { entities = config.models; } options.entities = entities; } if (options.asDefault) { this.options = options; } return yield typeorm.createConnection(options); }); } /** * get connection via name. * * @param {string} [connectName] * @returns {Connection} * @memberof TyepOrmStartupService */ getConnection(connectName) { var _a; return typeorm.getConnection(connectName !== null && connectName !== void 0 ? connectName : (_a = this.options) === null || _a === void 0 ? void 0 : _a.name); } destroying() { var _a, _b; (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info('close db connections'); (_b = typeorm.getConnectionManager().connections) === null || _b === void 0 ? void 0 : _b.forEach(c => c === null || c === void 0 ? void 0 : c.close()); } static ρAnn() { return { "name": "TypeormConnectionStatupService", "params": { "configureService": ["ctx"], "statupConnection": ["injector", "options", "config"], "createConnection": ["options", "config"], "getConnection": ["connectName"] } }; } }; exports.TypeormConnectionStatupService = tslib.__decorate([ ioc.Singleton() ], exports.TypeormConnectionStatupService); exports.TypeOrmHelper = class TypeOrmHelper { constructor() { } getConnection(connectName) { if (!this.service) { this.service = this.injector.get(exports.TypeormConnectionStatupService); } return this.service.getConnection(connectName); } getRepository(type, connectName) { return this.getConnection(connectName).getRepository(type); } getCustomRepository(type, connectName) { return this.getConnection(connectName).getCustomRepository(type); } getMongoRepository(type, connectName) { return this.getConnection(connectName).getMongoRepository(type); } static ρAnn() { return { "name": "TypeOrmHelper", "params": { "getConnection": ["connectName"], "getRepository": ["type", "connectName"], "getCustomRepository": ["type", "connectName"], "getMongoRepository": ["type", "connectName"] } }; } }; tslib.__decorate([ ioc.Inject(ioc.INJECTOR), tslib.__metadata("design:type", Object) ], exports.TypeOrmHelper.prototype, "injector", void 0); exports.TypeOrmHelper = tslib.__decorate([ ioc.Singleton(), tslib.__metadata("design:paramtypes", []) ], exports.TypeOrmHelper); const ObjectIDToken = ioc.tokenId('ObjectID'); const numbExp = /(int|float|double|dec|numeric|number)/; const intExp = /int/; const strExp = /(char|var|string|text)/; const boolExp = /(bool|bit)/; const timeExp = /(time|date)/; const arrayExp = /array/; const bytesExp = /(bytes|bytea)/; exports.TypeOrmModelParser = class TypeOrmModelParser extends boot.ModelParser { isObjectId(type) { return this._ObjectID && this._ObjectID === type; } setup() { let ObjectID = this._ObjectID; if (ObjectID) { this.getTypeMap() .register(ObjectID, (id) => new ObjectID(id)); } } getPropertyMeta(type) { let metas = {}; typeorm.getMetadataArgsStorage().columns.filter(col => col.target === type) .forEach(col => { metas[col.propertyName] = metas[col.propertyName] || []; metas[col.propertyName].push({ propertyKey: col.propertyName, dbtype: ioc.isString(col.options.type) ? col.options.type : '', type: this.getModeType(col) }); }); typeorm.getMetadataArgsStorage().relations.filter(col => col.target === type) .forEach(col => { metas[col.propertyName] = metas[col.propertyName] || []; let relaModel = ioc.isFunction(col.type) ? col.type() : undefined; metas[col.propertyName].push({ propertyKey: col.propertyName, provider: relaModel, type: (col.relationType === 'one-to-many' || col.relationType === 'many-to-many') ? Array : relaModel }); }); return metas; } isExtendBaseType(type, propmeta) { if (propmeta.dbtype) { if (intExp.test(propmeta.dbtype)) { return true; } } if (this.isObjectId(type)) { return true; } return super.isExtendBaseType(type, propmeta); } resolveExtendType(type, value, propmeta) { if (propmeta.dbtype) { if (intExp.test(propmeta.dbtype)) { return parseInt(value); } } if (this.isObjectId(type)) { return new this._ObjectID(value); } return super.resolveExtendType(type, propmeta); } getModeType(col) { let type = col.options.type; if (type) { if (ioc.isString(type)) { if (type === 'uuid') { return String; } else if (numbExp.test(type)) { return Number; } else if (boolExp.test(type)) { return Boolean; } else if (strExp.test(type)) { return String; } else if (timeExp.test(type)) { return Date; } else if (arrayExp.test(type)) { return Array; } else if (bytesExp.test(type)) { return Buffer; } else { return Object; } } return type; } switch (col.mode) { case 'objectId': type = this._ObjectID; break; } return type; } static ρAnn() { return { "name": "TypeOrmModelParser", "params": { "isObjectId": ["type"], "getPropertyMeta": ["type"], "isExtendBaseType": ["type", "propmeta"], "resolveExtendType": ["type", "value", "propmeta"], "getModeType": ["col"] } }; } }; tslib.__decorate([ ioc.Inject(ObjectIDToken), tslib.__metadata("design:type", Object) ], exports.TypeOrmModelParser.prototype, "_ObjectID", void 0); exports.TypeOrmModelParser = tslib.__decorate([ ioc.Singleton(boot.DefaultModelParserToken), ioc.Autorun('setup') ], exports.TypeOrmModelParser); exports.TypeOrmModule = class TypeOrmModule { static ρAnn() { return { "name": "TypeOrmModule", "params": {} }; } }; exports.TypeOrmModule = tslib.__decorate([ boot.DIModule({ regIn: 'root', imports: [ boot.ORMCoreModule ], providers: [ exports.TypeormConnectionStatupService, exports.TypeOrmHelper, exports.TypeOrmModelParser ] }) ], exports.TypeOrmModule); exports.ObjectIDToken = ObjectIDToken; //# sourceMappingURL=typeorm-adapter.js.map