Programming/Node.js

Node.js : MariaDB 연동

파란크리스마스 2019. 3. 2. 00:39
728x90

출처

/config/db_config.js

module.exports = (function() {
    return {
        host: "localhost",
        port : 10312,
        user: "root",
        password: "sqldba",
        database: "simplesns"
    }
})();

/config/dbHelper.js

const mariadb = require('mariadb');
var config = require('./db_config');    // ./는 현재 디렉토리를 나타냅니다

const pool = mariadb.createPool({
    host: config.host,
    port: config.port,
    user: config.user,
    password: config.password,
    database: config.database,
    connectionLimit: 5
});

function dbHelper() {
    //
    this.getConnection = function(callback) {
        pool.getConnection()
            .then(conn => {
                callback(conn);
            }).catch(err => {
            //not connected
        });
    };

    //
    this.getConnectionAsync = async function() {
        try {
            let conn = await pool.getConnection();
            // console.log("conn = " + conn); // { affectedRows: 1, insertId: 1, warningStatus: 0 }
            return conn;
        } catch (err) {
            throw err;
        }
        return null;
    };

    //
    this.sendJSON = function(response, httpCode, body) {
        var result = JSON.stringify(body);
        response.send(httpCode, result);
    };
}

module.exports = new dbHelper();

/api/user/UserService.js

var dbHelper = require('../../config/dbHelper');

// https://github.com/jareddlc/node-datatables/blob/master/server.js
function UserService() {
    this.getUserList = function(request, response) {
        dbHelper.getConnection(function(conn) {
            conn.query('SELECT * FROM member')
                .then((results) => {
                    // console.log(results); //[ {val: 1}, meta: ... ]

                    //Output
                    var output = {};
                    var temp = [];
                    output.datas = results;
                    
                    dbHelper.sendJSON(response, 200, output);
                })
                .then((res) => {
                    console.log('res = '+res); // { affectedRows: 1, insertId: 1, warningStatus: 0 }
                    conn.end();
                })
                .catch(err => {
                    //handle error
                    console.log(err);
                    conn.end();
                })
        });
    }
}

module.exports = new UserService();