我在学习 Node.js 时正在构建一个非常基本的 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
类,所有实体类都将从中继承。但我首先只是想让这个类自己正常工作。