Node 注解(装饰器)(MyBatis注解版)

import TransactionMysql = require('transaction-mysql');

let pool = new TransactionMysql({
    host: 'localhost',
    port: 3306,
    user: 'tujiawei',
    password: '123456',
    database: 'test'
});

// 注解
function Select(sql) {
    return function (target, key: string, descriptor) {
        descriptor.value = async function (...params) {
            return await pool.exec(sql, params);
        }
    }
}
// 事务注解
const Transaction = function (target, key: string, descriptor) {
    let originMethod = descriptor.value;
    descriptor.value = async function () {
        pool.begin();
        await originMethod.apply(this, [pool]);
        await pool.commit();
    }
};

class Service {
    conn;
    @Select('select * from t_table')
    async findAll() {}
    @Select('select * from t_table where id = ?')
    async findById(id) {}
    @Select('update t_table set name = ? where id = ?')
    async update(...args) {}
    @Transaction
    async updateTow(conn: any = {}) {
        let item1: any = await this.findById(4);
        let item2: any = await this.findById(3);
        item1 = item1[0];
        item2 = item2[0];
        conn.add('update t_table set name = ? where id = ?', [item1.name, item2.id]).add('update t_table set name = ? where id = ?', [item2.name, item1.id]);
    }
}

async function test() {
    let service = new Service();
    // await service.updateTow();
    let list = await service.findAll();
    console.log(list)
}

test();
// pool.begin().add('insert into t_table(name) values(?)', ['abc']).commit();
// new Service().findAll().then(list => {
//     console.log(list);
// });

相关推荐