UNPKG

@ones-open/node-host

Version:
83 lines (82 loc) 3.14 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildDBPromises = void 0; const mysql2_1 = __importDefault(require("mysql2")); const fs_1 = __importDefault(require("fs")); const config_1 = require("../../config"); let promisePool; function getPoolPromise() { if (promisePool) return promisePool; // create the connection to database const pool = mysql2_1.default.createPool({ host: config_1.config.local.mysql_host, user: config_1.config.local.mysql_user_name, password: config_1.config.local.mysql_user_password, database: config_1.config.local.mysql_database_name, waitForConnections: true, connectionLimit: 10, queueLimit: 0, }); promisePool = pool.promise(); return promisePool; } function formatImportSql(pluginId, originSql) { const regex = new RegExp('{{([^{}]*)}}', 'g'); if (!regex.test(originSql)) { throw new Error(`表名称不合法`); } // 替换表名 return originSql.replace(regex, `${pluginId}_$1`); } function formatSql(pluginId, originSql) { return originSql.replace(/(from|join|into|update)\s+(\w+)/gi, `$1 ${pluginId}_$2`); } async function ImportSql(pluginId, sqlFileName) { if (!sqlFileName) throw new Error(`非法参数: 参数不能为空!`); const fileStr = fs_1.default.readFileSync(`./workspace/${sqlFileName}`); const originSql = fileStr.toString(); const sql = formatImportSql(pluginId, originSql); await getPoolPromise().execute(sql); } async function Select(pluginId, originSql) { if (!originSql) throw new Error(`非法参数: 参数不能为空!`); const sql = formatSql(pluginId, originSql); const [rows] = await getPoolPromise().query(sql); return rows; } async function Count(pluginId, originSql) { if (!originSql) throw new Error(`非法参数: 参数不能为空!`); const sql = formatSql(pluginId, originSql); const [rows] = await getPoolPromise().query(sql); return Object.values(rows[0])[0]; } async function Exec(pluginId, operate, originSql) { if (!operate || !originSql) throw new Error(`非法参数: 参数不能为空!`); if (!['insert', 'update', 'delete', 'create', 'alter', 'drop'].includes(operate)) { throw new Error(`非法参数: operate 不能为${operate}`); } const sql = formatSql(pluginId, originSql); await getPoolPromise().execute(sql); } const buildDBPromises = (plugin) => { const pluginId = plugin.InstanceID; return { // @ts-expect-error 透传参数 ImportSql: (...args) => ImportSql(pluginId, ...args), // @ts-expect-error 透传参数 Select: (...args) => Select(pluginId, ...args), // @ts-expect-error 透传参数 Count: (...args) => Count(pluginId, ...args), // @ts-expect-error 透传参数 Exec: (...args) => Exec(pluginId, ...args), }; }; exports.buildDBPromises = buildDBPromises;