티스토리 뷰

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();
댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함