UNPKG

ts-api-core

Version:

Nodejs api framework core

350 lines 15.2 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseRouteSqlWrapper = void 0; const reqest_data_1 = require("../base/reqest.data"); const base_route_raw_wrapper_1 = require("./base.route.raw.wrapper"); const base_wrapper_1 = require("./base.wrapper"); const db_script_1 = require("../database/db.script"); class ScriptItem { } /** * 动态执行 `SQL` 请求数据加工基类 */ class BaseRouteSqlWrapper extends base_route_raw_wrapper_1.BaseRouteRawWrapper { constructor() { super(...arguments); this.TAG = "wrapper.sql"; } checkTable(table, type) { if (!table) { this.err(`执行失败:${type} 中未指定 table`); } } scriptErr(type) { this.err(`执行失败:${type} 脚本生成失败`); } deleteScript(config, script) { var _a; const cfg = config.delete; if (!cfg) { return; } this.checkTable(cfg.table, reqest_data_1.SQLRequestResultType.Delete); if (cfg.id && !cfg.id.field) { this.err(`执行失败:${reqest_data_1.SQLRequestResultType.Delete} 中未指定 field (ID字段名称)`); } const spt = cfg.id ? db_script_1.DBScript.deleteByIds(cfg.table, cfg.id.field, cfg.id.id) : db_script_1.DBScript.delete(Object, (_a = cfg.where) !== null && _a !== void 0 ? _a : '', { table: cfg.table }); if (spt) { script.push({ name: reqest_data_1.SQLRequestResultType.Delete, sql: spt, args: cfg.args }); } else { this.scriptErr(reqest_data_1.SQLRequestResultType.Delete); } } insertScript(config, script) { const cfg = config.insert; if (!cfg) { return; } this.checkTable(cfg.table, reqest_data_1.SQLRequestResultType.Insert); const spt = Array.isArray(cfg.value) ? this._batchInsert(cfg.table, cfg.value, cfg.options) : this._insert(cfg.table, cfg.value, cfg.options); if (spt) { script.push({ name: reqest_data_1.SQLRequestResultType.Insert, sql: spt.sql, args: spt.params }); } else { this.scriptErr(reqest_data_1.SQLRequestResultType.Insert); } } updateScript(config, script) { var _a; if (config.update) { const cfg = config.update; this.checkTable(cfg.table, reqest_data_1.SQLRequestResultType.Update); const spt = this._update(cfg.table, cfg.value, (_a = cfg.where) !== null && _a !== void 0 ? _a : '', { columnsOpts: cfg.options, conditionArgs: cfg.args, operatorType: cfg.operatorType }); if (spt) { script.push({ name: reqest_data_1.SQLRequestResultType.Update, sql: spt.sql, args: spt.params }); } else { this.scriptErr(reqest_data_1.SQLRequestResultType.Update); } } } insertUpdateScript(config, script) { if (config.insertUpdate) { const cfg = config.insertUpdate; this.checkTable(cfg.table, reqest_data_1.SQLRequestResultType.InsertUpdate); const spt = Array.isArray(cfg.value) ? this._batchInsertUpdate(cfg.table, cfg.value, { columnsOpts: cfg.options, operatorType: cfg.operatorType }) : this._insertUpdate(cfg.table, cfg.value, { columnsOpts: cfg.options, operatorType: cfg.operatorType }); if (spt) { script.push({ name: reqest_data_1.SQLRequestResultType.InsertUpdate, sql: spt.sql, args: spt.params }); } else { this.scriptErr(reqest_data_1.SQLRequestResultType.InsertUpdate); } } } queryScript(config, script) { if (config.query) { const cfg = config.query; this.checkTable(cfg.table, reqest_data_1.SQLRequestResultType.Query); let columns = cfg.fields === undefined ? '*' : []; if (cfg.fields !== undefined) { if (typeof cfg.fields === 'string') { columns = cfg.fields.split(',').map((v) => v.trim()); } else { columns = Object.keys(cfg.fields); } } const spt = db_script_1.DBScript.queryByTableColumns(cfg.table, columns, cfg.where, { alias: cfg.alias, joinSql: cfg.joinSql, extFields: cfg.extFields, page: cfg.page, pageSize: cfg.pageSize }); if (spt) { let totalSql = ''; // 获取总行数的 sql if (cfg.total === true) { totalSql = db_script_1.DBScript.rowCountSql(spt, 1); } else if (cfg.total !== undefined && typeof cfg.total === 'string' && cfg.total) { totalSql = cfg.total; } script.push({ name: reqest_data_1.SQLRequestResultType.Query, sql: spt, args: cfg.args, total: totalSql, page: cfg.page, pageSize: cfg.pageSize }); } else { this.scriptErr(reqest_data_1.SQLRequestResultType.Query); } } } executeRequest(context) { const _super = Object.create(null, { executeRequest: { get: () => super.executeRequest } }); return __awaiter(this, void 0, void 0, function* () { const config = context.route.config ? context.route.config : undefined; if (config) { const script = []; if (config.sql) { script.push({ name: reqest_data_1.SQLRequestResultType.SQL, sql: config.sql, args: config.args }); } this.deleteScript(config, script); this.insertScript(config, script); this.updateScript(config, script); this.insertUpdateScript(config, script); this.queryScript(config, script); if (script.length > 0) { this.context.dbConfig = config.db; let data = undefined; if (config.transaction === true || config.transaction === 1) { data = yield this.transaction((db) => __awaiter(this, void 0, void 0, function* () { return yield this.executeScript(script, true); })); } else { data = yield this.executeScript(script); } if (context.route.resp) { const result = !context.route.resp.src || Array.isArray(data) ? this.parserApiResult(context, context.route.resp, data) : this.parserApiResult(context, context.route.resp, data[context.route.resp.src]); return new base_wrapper_1.WrapperResult(result); } else { return new base_wrapper_1.WrapperResult(data); } } else { this.err('没有指定要执行的SQL脚本语句'); } } return _super.executeRequest.call(this, context); }); } /** 执行SQL脚本 */ executeScript(script, transaction = false) { return __awaiter(this, void 0, void 0, function* () { let result = {}; for (const item of script) { switch (item.name) { case reqest_data_1.SQLRequestResultType.Query: if (item.total) { let count = 0; let v = undefined; const rowCountSQL = item.total; if (transaction) { let data = yield this.query(rowCountSQL, item.args); if (data && data.length === 1) { count = Number(data[0].rowCount); } v = yield this.query(item.sql, item.args); } else { yield this.transaction((db) => __awaiter(this, void 0, void 0, function* () { let data = yield this.query(rowCountSQL, item.args); if (data && data.length === 1) { count = Number(data[0].rowCount); } v = yield this.query(item.sql, item.args); })); } result[item.name] = { page: item.page, total: count, totalPage: this.getPageCount(count, item.pageSize), items: v }; } else { const v = yield this.query(item.sql, item.args); result[item.name] = v; } break; default: yield this.executeSql(item.sql, item.args, (v, insertId, affectedRows, rows) => { result[item.name] = v; }); break; } } return script.length === 1 ? result[Object.keys(result)[0]] : result; }); } getPageCount(total, pageSize) { if (pageSize !== undefined && pageSize > 1) { return Math.ceil(total / pageSize); } else { return total; } } /** * 生成批量插入脚本 */ _batchInsert(table, entity, options) { if (!entity || entity.length === 0) { return undefined; } const columns = this.getColumns(entity, options, true); return db_script_1.DBScript.batchInsertByTableColumns(table, columns, entity); } /** * 生成批量插入脚本 */ _batchInsertUpdate(table, entity, options) { if (!entity || entity.length === 0) { return undefined; } const columns = this.getColumns(entity, options === null || options === void 0 ? void 0 : options.columnsOpts, true); return db_script_1.DBScript.batchInsertUpdateByTableColumns(table, columns, entity, options); } /** * 生成插入脚本 */ _insert(table, entity, options) { if (!entity) { return undefined; } const columns = this.getColumns(entity, options, true); return db_script_1.DBScript.insertByTableColumns(table, columns, entity); } /** * 生成更新脚本 */ _update(table, entity, condition, options) { if (!table || !entity) { return undefined; } const columns = this.getColumns(entity, options === null || options === void 0 ? void 0 : options.columnsOpts, false, true); return db_script_1.DBScript.updateByTableColumns(table, columns, entity, condition, options); } _insertUpdate(table, entity, options) { if (!entity) { return undefined; } const columns = this.getColumns(entity, options === null || options === void 0 ? void 0 : options.columnsOpts, false, true, true); return db_script_1.DBScript.insertUpdateByTableColumns(table, columns, entity, options); } getEntityKeys(entity, opts) { const _keys = Object.keys(entity); if (opts) { const map = new Map(); _keys.forEach((v, idx) => map.set(v, idx)); // 将注册的字段加入keys中,原因是由于没有默认值,可能字段不存在 for (const item in opts) { const k = opts[item]; const i = map.get(item); if (i === undefined || typeof _keys[i] === 'string') { const v = new db_script_1.ColumnParams(); if (i && i >= 0) { _keys[i] = v; } else { _keys.push(v); } } } } return _keys; } /** * 获取数据对象对应的列信息 * @param entity 数据对象 * @param allowInsert 列必须允许插入, 排除掉不允许插入的列 * @param allowUpdate 列必须允许更新, 排除掉不允许更新的列 * @returns */ getColumns(entity, opts, allowInsert, allowUpdate, excludePrimary) { const keys = []; const columns = this.getEntityKeys(entity, opts); // 将注册的字段加入keys中,原因是由于没有默认值,可能字段不存在 columns.forEach((k) => { if (k instanceof db_script_1.ColumnParams) { if (k.query === false) { return; } const i = keys.indexOf(k.propertyName); if ((allowInsert === true && k.inserted === false) || (allowUpdate === true && k.updated === false) || (excludePrimary === true && k.primary === true)) { if (i >= 0) { keys.splice(i, 1); } return; } if (i >= 0) { keys[i] = k; } else { keys.push(k); } } else if (typeof k === 'string') { keys.push(k); } }); return keys; } } exports.BaseRouteSqlWrapper = BaseRouteSqlWrapper; //# sourceMappingURL=base.route.sql.wrapper.js.map