UNPKG

@kwaeri/mysql-database-driver

Version:

The @kwaeri/mysql-database-driver component of the @kwaer/node-kit application platform.

79 lines 2.99 kB
/** * SPDX-PackageName: kwaeri/mysql-database-driver * SPDX-PackageVersion: 0.6.1 * SPDX-FileCopyrightText: © 2014 - 2022 Richard Winters <kirvedx@gmail.com> and contributors * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR MIT */ 'use strict'; // INCLUDES import * as mysql from 'mysql2'; import { DatabaseDriver } from '@kwaeri/database-driver'; // You'll need this line and the method definitions below // to create a new driver type...like for postgresql import debug from 'debug'; // DEFINES const DEBUG = debug('nodekit:mysql-database-driver'); /** * The MySQLDriver implements the DatabaseDriver for MySQL provider */ export class MySQLDriver extends DatabaseDriver { /** * @var { mysql.Pool } pool */ pool; /** * Class constructor */ constructor(config) { super(config); DEBUG(`Create connection pool`); // Fetch the connection pool: this.pool = mysql.createPool({ host: this.connection.host, port: (typeof this.connection.port == "string") ? parseInt(this.connection.port) : this.connection.port, database: this.connection.database, user: this.connection.user, password: this.connection.password }); } /** * This overload executes a prepared statement using mysql2. * * @param { string } query The placeholder (`?`) possessed query string to be executed. * @param { any[] } bits The optional bits to supplement when composing a prepared statement (one for each placeholder). * * @returns { Promise<QueryPromise> } A promise of a {@link QueryResult} * <br /> * **Example**: * ```typescript * // An example using prepared statements: * const dbo = new MySQLDriver( connection ); * * const { rows, fields } = await dbo.query( "select * from table where `first_name`=? and `age`>=?;", ["Richard", 35] ); * ``` */ async query(query, bits) { try { // Create a promise wrapper for a connection: const promisePool = this.pool.promise(); if (bits && bits.length) DEBUG(`New MySQL 'query' with query: '${query}', and bits: '${bits.join(`', '`)}'`); else DEBUG(`New MySQL 'query' with query string: '${query}'`); // Execute the query: const [rows, fields] = (bits && bits.length) ? await promisePool.execute(query, bits) : await promisePool.execute(query); DEBUG(`Query returned 'fields' with:`); DEBUG(`'${fields}'`); DEBUG(`Query returned 'rows' with:`); DEBUG(`'${rows}'`); // Return a promise resolution: return Promise.resolve({ rows, fields }); } catch (error) { DEBUG(`Error: ${error}`); return Promise.reject(error); } } } //# sourceMappingURL=mysql-database-driver.mjs.map