简体   繁体   English

如何包装 node.js function 以有组织的方式访问它们

[英]How to wrap node.js function to access them in organized way

So I come to this, I want to write into a DB and do other operations to work with my program logic, this is the guide that I'm following Node.js Class Creation :所以我来到这里,我想写入数据库并执行其他操作以使用我的程序逻辑,这是我遵循Node.js Class 创建的指南:

//## This is my mysql_test.js file
function MySQL(){
var mysql = require('mysql'); 

var con = mysql.createConnection({
    //data omitted
});


function AppendRecordset (req, res){
    con.connect(function(err) {
      if (err) throw err;
      console.log("Connected!");      
      con.query(req, function (err, res) {
        if (err) throw err;
        console.log("1 record inserted");
      });
    });    
}

function UpdateRecordset (req, res) {
    con.connect(function(err) {
      if (err) throw err;      
      con.query(req, function (err, res) {
        if (err) throw err;
        console.log(result.affectedRows + " record(s) updated");
      });
    });    
}

function DeleteRecordset (req, res){
    con.connect(function(err) {
      if (err) throw err;      
      con.query(req, function (err, res) {
        if (err) throw err;
        console.log("Number of records deleted: " + result.affectedRows);
      });
    });    
}

function GetRecordset (req, res) {
    con.connect(function(err) {
      if (err) throw err;
      con.query(req, function (err, res, fields) {
        if (err) throw err;
        console.log(result);
      });
    });
}
}

I then have in a separate file(s) my app logic, and want to use what of the above as an object/class so I wrote this accordingly to that guide:然后,我将我的应用程序逻辑放在一个单独的文件中,并希望将上述内容用作对象/类,因此我根据该指南编写了以下内容:

//##this is inside my main app file
//declare the sql processor
require('./mysql_test.js');
var DB = MySQL();
DB.AppendRecordset(sql_string, res);  //sql_string contains a valid SQL statement

But when I try to acces it using `` I get this error message: ReferenceError: MySQL is not defined what am I doing wrong?但是,当我尝试使用 `` 访问它时,我收到以下错误消息: ReferenceError: MySQL is not defined我做错了什么?

I think these functions handle your routes, so I didn't change them.我认为这些功能可以处理您的路线,所以我没有更改它们。 Because I don't know how your router is desined.因为我不知道你的路由器是如何设计的。

Create a file dbHangler.js and write this single function:创建一个文件dbHangler.js并编写此单个 function:

const mysql = require('mysql'); 

let con;

exports.execQuery = (query) => {
  return new Promise((resolve, reject) => {
    if(!con) {
      con = mysql.createConnection({
        //data omitted
      });
    }
    con.connect(function(err) {
        if(err) {
          reject(err);
        }
        else {
          console.log("Connected!");
          con.query(query, function (err, res) {
            if (err) {
              reject(err);
            }
            else {
              resolve(res);
            }
          });
        }
      });    
  });
};

In your dedicated.js file, now you can write:在您的dedicated.js文件中,现在您可以编写:

const dbObject = require('path/to/dbHandler');

function AppendRecordset (req, res){
    dbObject.execQuery(req)
      .then(result => {
        console.log(result.affectedRows + " record(s) updated");
      })
      .catch(error => {
        // handle error
      });
}

function AppendRecordset (req, res){
    dbObject.execQuery(req)
      .then(result => {
        console.log("Number of records deleted: " + result.affectedRows);
      })
      .catch(error => {
        // handle error
      });
}

function AppendRecordset (req, res){
    dbObject.execQuery(req)
      .then(result => {
        console.log(result);
      })
      .catch(error => {
        // handle error
      });
}

UPDATE更新

I hope this one helps you.我希望这个对你有帮助。

DbHandler.js

const mysql = require('mysql');

class DbHandler {
  constructor(config) {
    let self = this;
    self.dbConfig = config;
    self.connection = mysql.createConnection({
      //data omitted
    });
  }

  queryExecuter(query) {
    let self = this;
    return new Promise((resolve, reject) => {
      self.connection.connect(function (err) {
        if (err) {
          reject(err);
        }
        else {
          console.log("Connected!");
          self.connection.query(query, function (err, res) {
            if (err) {
              reject(err);
            }
            else {
              resolve(res);
            }
          });
        }
      });
    });
  }

  AppendRecordset(query) {
    let self = this;
    return self.queryExecuter(query)
      .then(result => {
        console.log("1 record inserted");
        return result;
      })
      .catch(error => {
        // handle error
        throw error;
      });
  }

  UpdateRecordset(query) {
    let self = this;
    return self.queryExecuter(query)
      .then(result => {
        console.log(result.affectedRows + " record(s) updated");
        return result;
      })
      .catch(error => {
        // handle error
        throw error;
      });
  }

  // and other functions
}

module.exports = DbHandler;

And use it like below:并像下面这样使用它:

let DB = require('/path/to/DbHandler');

let myDb = new DB(/* db config */);

db.UpdateRecordset('your query')
  .then(res => {
    console.log(res);
  })
  .catch(err => {
    console.log(err);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将此 node.js 片段包装在 function 中的最佳方法是什么? - What is the best way to wrap this node.js snippet in a function? 如何在 Node.js 中的 function 外部访问 await function 变量 - How to access await function variable outside function in Node.js 如何将异步函数调用包装到Node.js或Javascript中的同步函数中? - How to wrap async function calls into a sync function in Node.js or Javascript? 这种在node.js中访问mongodb的方法是否可以接受? - Is this way to access mongodb in node.js acceptable? 在 node.js 中访问动态 function 名称 - Access dynamic function name in node.js Node.js模块功能的访问参数 - Access parameter of Node.js module function 如何在URL中发送多个参数以及如何在Node.js / Express中的GET路由中访问它们 - How to send more than 1 parameters in url and how to access them in my GET route in Node.js/Express 如何在Node.js中的JavaScript中包装或代理另一个对象 - How to wrap or proxy another object in JavaScript in Node.js 将Powershell对象传递给Node.JS / Electron并将其包装在HTML标记中 - Passing Powershell Objects to Node.JS / Electron and wrap them in HTML Tags 如何在本地访问 Node.JS 项目? - How to access Node.JS project locally?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM