代码之家  ›  专栏  ›  技术社区  ›  MathieuAuclair

如何获取父对象(模块NodeJS)的函数

  •  0
  • MathieuAuclair  · 技术社区  · 9 年前

    我正在开发一个nodejs模块,该模块将处理一个项目的所有SQL内容,我对该语言有一个问题,javascript中没有父关系,我不能复制我的连接,否则我会出现握手错误,那么我如何引用它呢。没有实例化安装对象的连接。

    我知道这个问题可能有点宽泛,但如果有人有解决这个问题的方法或想法,我想听听,所以请随意提一些建议!

    require("dotenv").config();
    const mysql = require("mysql");
    const sqlstring = require("sqlstring");
    
    function setup(){
        this.connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password : process.env.PASSWORD,
            database : 'DISCORD'
        }), 
        this.connect = function(){
            this.connection.connect(function(err){
                if(err){
                    throw err;
                }
            });
        },
        this.makeRequest = function(requestName, param){
            this.connection.query("SELECT SQLQUERY FROM QUERYLIST WHERE NAME = " + this.formatString(requestName),function(err, result){
                if(err){
                    throw err;
                } else{
                     //-------- CAN'T CALL THIS NOT IN SETUP OBJECT ANYMORE
                    this.connection.query(result[0].SQLQUERY + this.formatString(param), function(err2, result2){
                        return result2;
                    });
                }
            });
        },
        this.formatString = function(string){
            return sqlstring.escape(string);    
        }
    }
    

    this.makeRequest = function(requestName, param){
        this.connection.query(result[0].SQLQUERY + this.formatString(param),this.test);
    },
    this.test = function(err, result){
        //stuff
    }
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   GabLeRoux Tidder Jail    9 年前

    我认为您需要的是跨不同的模块重用mysql连接。有一个类似的问题显示了如何做到这一点: How to properly pass mysql connection to routes with express.js

    Pool 变量 as shown in the first answer.