mustache
语法select * from {{key1}}
字符中{{key1}}会进行匹配map中的key
例如:
let sql = select * from {{key1}}; let tableMapper = { "key1": "course", } let result = mustache.render(sql, tableMapper); console.log('result:', result);
此段代码中select * from {{key1}}
会被替换为select * from course
dbmysql.ts
let mysql = require('mysql2'); let mustache = require('mustache'); module.exports = class dbmysql { private mysqlConnectPool: any; private tableMapper = { "key1": "course", } init(dbConfig: any): void { try { this.mysqlConnectPool = mysql.createPool(dbConfig); console.debug('MySql Adapter Pool generated successfully'); } catch (error) { console.error('[mysql.connector][init][Error]: ', error); throw new Error('failed to initialized pool'); } } executeQuery(sql: any, params: any): any { return new Promise((resolve, reject) => { this.mysqlConnectPool.getConnection(function (err: any, conn: any) { if (err) { reject(err); } else { conn.release(); conn.execute(sql, params, function (err: any, rows: any) { if (err) { reject(err); } else { resolve(rows); } }); } }); }); } // 查找this.tableMapper键匹配表名 renderQuery(sql: any, params?: any): any { sql = mustache.render(sql, this.tableMapper); return this.executeQuery(sql, params); } }