mysql-promise.js 1.3 KB
'use strict';

const mysql = require('promise-mysql');
const config = require('../config/config');

class MysqlPromise {
    constructor() {
        this.connect();
    }

    connect() {
        if (this.conn) {
            return Promise.resolve(this.conn);
        }

        return mysql.createConnection({
            host: config.mysql.host,
            user: config.mysql.user,
            password: config.mysql.password,
            port: config.mysql.port,
            database: config.mysql.database
        }).then(conn => {
            this.conn = conn;
            return conn;
        }).catch(err => {
            console.error(`mysql connect fail, err: ${err.message}`);
            return null;
        });
    }

    query(sql, values) {
        return this.connect().then(d => {
            return d.query(sql, values);
        }).catch(err => {
            console.error(`mysql query, err: ${err.message}`);
            return [];
        });
    }

    close(data) {
        return this.connect().then(d => {
            return d.end();
        }).then(d => {
            this.conn = null;
            return data;
        }).catch(err => {
            this.conn = null;
            console.error(`mysql close, err: ${err.message}`);
            return data;
        });
    }
}

module.exports = MysqlPromise;