类应如何关闭连接池?

问题描述

在学习Node的同时,我正在构建一个非常基本的ORM。我让构造函数当前接受名称或id参数,但不能同时接受。如果提供了名称,则该类将在数据库中创建记录。如果提供了ID,它将查找记录。这是完整的文件

const MysqL = require('MysqL2/promise');
const { v4: uuid } = require('uuid');

const pool = require('../helpers/pool.js');
const xor = require('../helpers/xor.js');

class List {
    constructor({ name = null,id = null} = {}) {
        if (!xor(name,id)) {
            throw new TypeError('Lists must have either a name or an id');
        }
        this.table_name = 'lists';
        if (name) {
            this.name = name;
            this.uuid = uuid();
            this.#insert_record();
            return;
        }
        this.id = id;
        this.#retrieve_record();
    }

    async #insert_record() {
        await pool.query(
            `INSERT INTO ${this.table_name} SET ?`,{
                name: this.name,uuid: this.uuid
            }
        ).then(async (results) => {
            this.id = results[0].insertId;
            return this.#retrieve_record();
        });
    }

    async #retrieve_record() {
        return await pool.execute(
            `SELECT * FROM ${this.table_name} WHERE id = ?`,[this.id]
        ).then(([records,fields]) => {
            this.#assign_props(records[0],fields);
            pool.end();
        })
    }

    #assign_props(record,fields) {
        fields.forEach((field) => {
            this[field.name] = record[field.name];
        })
        console.log(this);
    }
}

const list = new List({name: 'my list'});
const db_list = new List({id: 50});

您可能会看到问题按原样运行。我收到间歇性错误。有时一切正常。通常,我首先看到检索到的列表的控制台日志,然后看到新列表的日志。但是有时,在进行插入操作之前,池会因检索而关闭

我尝试将池放置在类中,但这只是引起了其他错误

那么,让ORM类使用连接池的正确方法是什么?请注意,我在学习过程中正在构建功能,最终将有一个Table类,所有实体类都将从该类继承。但是我首先只是想让这一堂课独自发挥作用。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)