@thermopylae/core.mysql
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

@thermopylae/core.mysql

Version Node Version Documentation License: MIT

MySQL client.

Install

npm install @thermopylae/core.mysql

Description

This package contains client for MySQL Server. It uses mysql2 npm package as underlying implementation.
MySQLClient allows you to establish pooled connections or pool cluster connections. Write & Read pools are abstracted regardless of pooled or pool cluster connections.

Usage

Package exports a singleton of MySQLClient class, called MySqlClientInstance, which needs to be configured before being used. After that you can create connections and perform queries.
Let's take a look at the following example which demonstrates how the package can be used.

import {
    MySqlClientInstance,
    QueryType,
    DebuggableEventType,
    ResultSetHeader,
    RowDataPacket,
    initLogger as initCoreMysqlLogger 
} from '@thermopylae/core.mysql';
import { LoggerManagerInstance, OutputFormat } from '@thermopylae/core.logger';

(async function main() {
    /* Firstly init logging system */
    LoggerManagerInstance.formatting.setDefaultFormattingOrder(OutputFormat.PRINTF);
    LoggerManagerInstance.console.createTransport({ level: 'info' });
    initCoreMysqlLogger();
    
    /* Configure MySQL */
    MySqlClientInstance.init({
        pool: {
            host: '127.0.0.1',
            port: 3306,
            user: 'your-user',
            password: 'your-password',
            database: 'your-database'
        },
        /*
            // alternative to `pool` is `poolCluster` option
            poolCluster: {
                nodes: {
                    MASTER: { host: '127.0.0.1', port: 3306 },
                    SLAVE: { host: '127.0.0.1', port: 3307 }
                }
            }
         */
        sessionVariablesQueries: ["SET @id = 'A';"],
        attachDebugListeners: new Set<DebuggableEventType>(['connection', 'enqueue'])
    });
    
    /* Perform queries  */
    let accountId: string;
    let connection = await MySqlClientInstance.getConnection(QueryType.WRITE);
    
    try {
        const [results] = await connection.execute<ResultSetHeader>(
            `INSERT INTO Account (username, passwordHash, email) VALUES (?, ?, ${MySqlClientInstance.escape('email@email.com')});`,
            ['username', 'hash']
        );

        accountId = String(results.insertId);
    } finally {
        connection.release(); // VERY IMPORTANT! Connection needs to be released
    }

    connection = await MySqlClientInstance.getConnection(QueryType.READ);
    try {
        const [results] = await connection.query<RowDataPacket[]>(`SELECT * FROM Account WHERE id=${accountId};`);

        if (results.length === 1) {
            console.log(`Account found: ${JSON.stringify(results[0])}`);
        }
    } finally {
        connection.release(); // VERY IMPORTANT! Connection needs to be released
    }
    
    /* Shutdown */
    await MySqlClientInstance.shutdown();
})();

API Reference

API documentation is available here.

It can also be generated by issuing the following commands:

git clone git@github.com:marinrusu1997/thermopylae.git
cd thermopylae
yarn install
yarn workspace @thermopylae/core.mysql run doc

Author

👤 Rusu Marin

📝 License

Copyright © 2021 Rusu Marin.
This project is MIT licensed.

Package Sidebar

Install

npm i @thermopylae/core.mysql

Weekly Downloads

2

Version

1.0.1

License

MIT

Unpacked Size

21.4 kB

Total Files

17

Last publish

Collaborators

  • marinrusu1997