UNPKG

@joktec/mysql

Version:

JokTec - MySql Service

241 lines 10.2 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MysqlRepo = void 0; const core_1 = require("@joktec/core"); const utils_1 = require("@joktec/utils"); const lodash_1 = require("lodash"); const helpers_1 = require("./helpers"); const mysql_exception_1 = require("./mysql.exception"); const mysql_service_1 = require("./mysql.service"); let MysqlRepo = class MysqlRepo { constructor(mysqlService, model, conId = core_1.DEFAULT_CON_ID) { this.mysqlService = mysqlService; this.model = model; this.conId = conId; } async onModuleInit() { this.logService.setContext(this.constructor.name); } onApplicationBootstrap() { } get entityManager() { return this.mysqlService.getEntityManager(this.conId); } get repository() { return this.mysqlService.getRepository(this.model, this.conId); } transform(docs) { if ((0, lodash_1.isNil)(docs)) return null; if ((0, lodash_1.isArray)(docs) && !docs.length) return []; const transformDocs = (0, utils_1.plainToInstance)(this.model, (0, utils_1.toArray)(docs)); return ((0, lodash_1.isArray)(docs) ? transformDocs : transformDocs[0]); } qb(query = {}, opts = {}) { const metadata = Reflect.getMetadata('searchableKeywords', this.model); const qb = this.repository.createQueryBuilder(this.model.name); if (query.condition) helpers_1.MysqlHelper.applyCondition(qb, query.condition); if (query.select) helpers_1.MysqlHelper.applyProjection(qb, query.select); if (query.sort) helpers_1.MysqlHelper.applyOrder(qb, query.sort); helpers_1.MysqlHelper.applyPagination(qb, query); if (query.populate) helpers_1.MysqlHelper.applyRelations(qb, query.populate); if (opts.withDeleted) qb.withDeleted(); if (opts.comment) qb.comment(opts.comment); if (opts.cache) qb.cache(opts.cache); if (opts.lock) { if (opts.lock.mode === 'optimistic') qb.setLock('optimistic', opts.lock.version); else qb.setLock(opts.lock.mode, undefined, opts.lock.tables).setOnLocked(opts.lock.onLocked); } return qb; } finder(query = {}, opts = {}) { const options = helpers_1.MysqlFinder.parseFilter(query); const { limit, offset } = helpers_1.MysqlFinder.parsePagination(query); if (query.select) options.select = helpers_1.MysqlFinder.parseProjection(query.select); if (query.sort) options.order = helpers_1.MysqlFinder.parseOrder(query.sort); if (offset !== undefined) options.skip = offset; if (limit !== undefined) options.take = limit; if (query.populate) options.relations = helpers_1.MysqlFinder.parseRelations(query.populate); return { ...opts, ...options }; } whereById(pkValue) { const primaryColumns = this.repository.metadata.primaryColumns.map(pk => pk.propertyName); return primaryColumns.reduce((curr, acc) => { curr[acc] = pkValue; return curr; }, {}); } async paginate(query, opts = {}) { const findQuery = { ...query }; const countQuery = (0, lodash_1.omit)(query, ['select', 'page', 'limit', 'offset', 'sort']); const [items, total] = await Promise.all([this.find(findQuery, opts), this.count(countQuery, opts)]); return { items, total }; } async find(query, opts = {}) { const options = this.finder(query, opts); const docs = await this.repository.find(options); return this.transform(docs); } async count(query, opts = {}) { const options = this.finder(query, opts); return this.repository.count(options); } async findOne(cond, query = {}, opts = {}) { const condition = {}; if (!(0, lodash_1.isObject)(cond)) Object.assign(condition, { ...this.whereById(cond) }); else Object.assign(condition, cond); const mergeQuery = Object.assign({}, query, { condition }); const options = this.finder(mergeQuery, opts); const doc = await this.repository.findOne(options); return this.transform(doc); } async create(body, opts = {}) { const transformBody = this.transform(body); const entity = this.repository.create(transformBody); return this.repository.save(entity, opts); } async update(cond, body, options = {}) { const condition = {}; if (!(0, lodash_1.isObject)(cond)) Object.assign(condition, { ...this.whereById(cond) }); else Object.assign(condition, cond); const entity = await this.findOne(condition, options); if (!entity) return null; const transformBody = this.transform({ ...entity, ...body }); const doc = await this.repository.save(transformBody, options); return this.transform(doc); } async delete(cond, opts = {}) { const entity = await this.findOne(cond, opts); if (!entity) return null; const func = opts?.force ? this.repository.remove : this.repository.softRemove; const doc = await func(entity); return this.transform(doc); } async restore(cond, opts = {}) { const entity = await this.findOne(cond, opts); if (!entity) return null; const doc = await this.repository.recover(entity); return this.transform(doc); } async upsert(body, onConflicts, opts = {}) { const transformBody = this.repository.create(body); const result = await this.repository.upsert(transformBody, { ...opts, conflictPaths: onConflicts }); return this.transform(result.generatedMaps[0]); } async bulkUpsert(body, onConflicts, opts = {}) { const chunkSize = (0, utils_1.toInt)(opts?.chunkSize, 1000); const chunkItems = (0, lodash_1.chunk)(body, chunkSize); const results = []; for (const chunkItem of chunkItems) { const transformBody = this.repository.create(chunkItem); const result = await this.repository.upsert(transformBody, { ...opts, conflictPaths: onConflicts }); const transformResult = this.transform(result.generatedMaps); results.push(transformResult); } return results.flat(); } }; exports.MysqlRepo = MysqlRepo; __decorate([ (0, core_1.Inject)(), __metadata("design:type", core_1.ConfigService) ], MysqlRepo.prototype, "configService", void 0); __decorate([ (0, core_1.Inject)(), __metadata("design:type", core_1.LogService) ], MysqlRepo.prototype, "logService", void 0); __decorate([ mysql_exception_1.MysqlCatch, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], MysqlRepo.prototype, "paginate", null); __decorate([ mysql_exception_1.MysqlCatch, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], MysqlRepo.prototype, "find", null); __decorate([ mysql_exception_1.MysqlCatch, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], MysqlRepo.prototype, "count", null); __decorate([ mysql_exception_1.MysqlCatch, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Object]), __metadata("design:returntype", Promise) ], MysqlRepo.prototype, "findOne", null); __decorate([ mysql_exception_1.MysqlCatch, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], MysqlRepo.prototype, "create", null); __decorate([ mysql_exception_1.MysqlCatch, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Object]), __metadata("design:returntype", Promise) ], MysqlRepo.prototype, "update", null); __decorate([ mysql_exception_1.MysqlCatch, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], MysqlRepo.prototype, "delete", null); __decorate([ mysql_exception_1.MysqlCatch, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], MysqlRepo.prototype, "restore", null); __decorate([ mysql_exception_1.MysqlCatch, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Array, Object]), __metadata("design:returntype", Promise) ], MysqlRepo.prototype, "upsert", null); __decorate([ mysql_exception_1.MysqlCatch, __metadata("design:type", Function), __metadata("design:paramtypes", [Array, Array, Object]), __metadata("design:returntype", Promise) ], MysqlRepo.prototype, "bulkUpsert", null); exports.MysqlRepo = MysqlRepo = __decorate([ (0, core_1.Injectable)(), __metadata("design:paramtypes", [mysql_service_1.MysqlService, Object, String]) ], MysqlRepo); //# sourceMappingURL=mysql.repo.js.map