@megaorm/mysql
Version:
This package provides a simple, high-level, unified API for interacting with MySQL databases.
220 lines • 8.91 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MySQL = void 0;
const promise_1 = require("mysql2/promise");
const errors_1 = require("@megaorm/errors");
const errors_2 = require("@megaorm/errors");
const errors_3 = require("@megaorm/errors");
const errors_4 = require("@megaorm/errors");
const errors_5 = require("@megaorm/errors");
const errors_6 = require("@megaorm/errors");
const test_1 = require("@megaorm/test");
/**
* MySQL driver responsible for creating MySQL connections.
* @implements `MegaDriver` interface.
* @example
*
* // Create a new MySQL driver
* const driver = new MySQL({
* database: 'main', // Your db name
* password: 'root', // Your db password,
* user: 'root', // Your db user name
* host: 'localhost', // Your db host
* });
*
* // Create connection
* const connection = await driver.create();
*
* // Execute your queries
* const result = await connection.query(sql, values);
* console.log(result);
*
* // Begin a transaction
* await connection.beginTransaction();
*
* // Commit transaction
* await connection.commit();
*
* // Rollback transaction
* await connection.rollback();
*
* // Close connection
* await connection.close();
*/
class MySQL {
/**
* Constructs a MySQL driver with the given options.
* @param options - Configuration options for the MySQL driver.
* @example
*
* // Create a new MySQL driver
* const driver = new MySQL({
* database: 'main', // Your db name
* password: 'root', // Your db password,
* user: 'root', // Your db user name
* host: 'localhost', // Your db host
* });
*
* // Create connection
* const connection = await driver.create();
*
* // Execute your queries
* const result = await connection.query(sql, values);
* console.log(result);
*
* // Begin a transaction
* await connection.beginTransaction();
*
* // Commit transaction
* await connection.commit();
*
* // Rollback transaction
* await connection.rollback();
*
* // Close connection
* await connection.close();
*/
constructor(options) {
if (!(0, test_1.isObj)(options)) {
throw new errors_2.CreateConnectionError(`Invalid MySQL options: ${String(options)}`);
}
// Enables support for BIGINT types
options['supportBigNumbers'] = true;
// Dates are returned as strings
options['dateStrings'] = true;
// Decimal numbers are returned as JavaScript Number types
options['decimalNumbers'] = true;
this.options = options;
this.id = Symbol('MySQL');
}
/**
* Creates a new MySQL connection.
* @returns A `Promise` that resolves with a new MySQL connection.
* @throws `CreateConnectionError` If connection creation fails.
* @example
*
* // Create a new MySQL driver
* const driver = new MySQL({
* database: 'main', // Your db name
* password: 'root', // Your db password,
* user: 'root', // Your db user name
* host: 'localhost', // Your db host
* });
*
* // Create connection
* const connection = await driver.create();
*
* // Execute your queries
* const result = await connection.query(sql, values);
* console.log(result);
*
* // Begin a transaction
* await connection.beginTransaction();
*
* // Commit transaction
* await connection.commit();
*
* // Rollback transaction
* await connection.rollback();
*
* // Close connection
* await connection.close();
*/
create() {
return new Promise((resolve, reject) => {
(0, promise_1.createConnection)(this.options)
.then((connection) => {
const mysql = {
id: Symbol('MegaConnection'),
driver: this,
query(sql, values) {
return new Promise((resolve, reject) => {
if (!(0, test_1.isStr)(sql)) {
return reject(new errors_1.QueryError(`Invalid query: ${String(sql)}`));
}
if ((0, test_1.isDefined)(values)) {
if (!(0, test_1.isArr)(values)) {
return reject(new errors_1.QueryError(`Invalid query values: ${String(values)}`));
}
values.forEach((value) => {
if (!(0, test_1.isNum)(value) && !(0, test_1.isStr)(value)) {
return reject(new errors_1.QueryError(`Invalid query value: ${String(value)}`));
}
});
}
connection
.execute(sql, values)
.then(([result, fields]) => {
// Handle SELECT queries
if (/^\s*SELECT/i.test(sql))
return resolve(result);
// Handle INSERT queries
if (/^\s*INSERT/i.test(sql)) {
// Test if it's a single insert or bulk insert
if (result.affectedRows === 1) {
return resolve(result.insertId); // Return PK for single insert
}
return resolve(undefined); // Return undefined for bulk insert
}
// Handle other query types
return resolve(undefined);
})
.catch((error) => reject(new errors_1.QueryError(error.message)));
});
},
close() {
return new Promise((resolve, reject) => {
connection
.end()
.then(() => {
const assign = (Error) => {
return function reject() {
return Promise.reject(new Error('Cannot perform further operations once the connection is closed'));
};
};
// Reset
mysql.close = assign(errors_3.CloseConnectionError);
mysql.query = assign(errors_1.QueryError);
mysql.beginTransaction = assign(errors_5.BeginTransactionError);
mysql.commit = assign(errors_4.CommitTransactionError);
mysql.rollback = assign(errors_6.RollbackTransactionError);
// Resolve
resolve();
})
.catch((error) => reject(new errors_3.CloseConnectionError(error.message)));
});
},
beginTransaction() {
return new Promise((resolve, reject) => {
connection
.beginTransaction()
.then(resolve)
.catch((error) => reject(new errors_5.BeginTransactionError(error.message)));
});
},
commit() {
return new Promise((resolve, reject) => {
connection
.commit()
.then(resolve)
.catch((error) => reject(new errors_4.CommitTransactionError(error.message)));
});
},
rollback() {
return new Promise((resolve, reject) => {
connection
.rollback()
.then(resolve)
.catch((error) => reject(new errors_6.RollbackTransactionError(error.message)));
});
},
};
// Resolve with a new MgeaConnection
return resolve(mysql);
})
.catch((error) => reject(new errors_2.CreateConnectionError(error.message)));
});
}
}
exports.MySQL = MySQL;
//# sourceMappingURL=index.js.map