2017-06-28 9 views
2

私はクエリを実行し、expressを使ってそれを表示するモジュールを持っています。module.exportsにパラメータを追加しますか?

module.exports.runQuery =function(req,res){ 
    //gets connection 
    connection.on('connect', function(err) { 
     console.log("success"); 
     //if connection works run the request 
     executeStatement(); 
    }); 
    function executeStatement() { 
    request = new Request("INSERT SQL HERE", function(err, rowCount){ 

私ができることを望むのは、module.exports.runqueryパラメータにsqlを含む文字列を渡すことです。これを行う方法、またはSQLの文字列を取得する簡単な方法はありますか?

答えて

0

あなたはリクエストオブジェクトのSQLクエリーを含むプロパティを添付することができます。

server.js

const app = require('express')() 
const {runQuery} = require('./query') 

app.get('/', function (req, res) { 
    req.sqlQuery = "INSERT SQL HERE" 
    runQuery(req, res) 
}) 

クエリ。 JS

module.exports.runQuery = function(req, res) { 
    connection.on('connect', function(err) { 
    executeStatement() 
    }) 

    function executeStatement() { 
    request = new Request(req.sqlQuery, function() {}) 
    } 
} 

それとも、またmiddlwareを通してそれを行うことができます。

function middleware(req, res, next) { 
    req.sqlQuery = "INSERT SQL HERE" 
    next() 
} 

app.get('/', middleware, runQuery) 
0

module.exportsの代わりにexports.function_nameを使用すると、任意のパラメータを使用できます。 module.expotsは、オブジェクトをエクスポートするためのものであり、関数ではありません。 exports.func_nameは、ファイルから関数をエクスポートするために使用できますが、

例:

exports.function_name = function (params){ 
. . . 
} 

が続いて使用します。

var helper = require('path to module') 
helper.function_name(params) 
0

は別のパラメータとしてSQL文字列を追加します。

module.exports.runQuery =function(req, res, sqlQuery){ 
    //gets connection 
    connection.on('connect', function(err) { 
     console.log("success"); 
     //if connection works run the request 
     executeStatement(sqlQuery); 
    }); 
    function executeStatement(sqlQuery) { 
    request = new Request(sqlQuery, function(err, rowCount){ 

次に、runQueryを呼び出している間。

var something = require('file'); 
sqlQuery = "YOUR QUERY HERE"; 
something.runQuery(req, res, sqlQuery); 

runQueryメソッドを名前が示すとおりに使用している場合。その後、req, resは必要ありません。これを行うには良い方法は

module.exports.runQuery =function(sqlQuery, callback){ 
    //gets connection 
    connection.on('connect', function(err) { 
     console.log("success"); 
     //if connection works run the request 
     result = executeStatement(sqlQuery); 
     callback(result); 
    }); 
    function executeStatement() { 
    request = new Request(sqlQuery, function(err, rowCount){ 
    //after finishing 
    return result; 
    } 

だろうその後の呼び出しは

var something = require('file'); 
sqlQuery = "YOUR QUERY HERE"; 
something.runQuery(sqlQuery, function(result) { 
    res.send(result); 
}); 
だろう
関連する問題