数据库
首页 > 数据库> > 一个typescript版本的dao(数据库访问)层的封装

一个typescript版本的dao(数据库访问)层的封装

作者:互联网

首先学会使用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

对mysql的dao层的封装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);
    }
}

标签:typescript,封装,err,key1,dao,let,sql,tableMapper,any
来源: https://www.cnblogs.com/codebai/p/16580634.html