这可能很容易,但我一直无法正确地将它拼凑在一起。
我正在尝试使用 Sequelize NPM 调用我构建的存储过程,然后我想用来自 express api 的 GET 请求触发它,并将过程的输出返回给 api。
这是我的 Sequelize 部分代码的样子....
// Testing sproc //
const Retrieve = (testName) => connection.testdata_connection.query("EXEC [SPROC] [INPUTS]")
module.exports = {
tests: Tests(),
retrieve: Retrieve()
};
这部分“connection.testdata_connection”只是建立我与数据库的连接,我已经对此进行了测试,我知道这部分已设置。我希望能够用类似...
const query = require('./database/queries'); ///Imports sequelize queries
const app = express();
app.get('/decrypt', function(req,res){
query.retrieve()
})
})
这根本行不通。现在,如果我在查询文件中做这样的事情......
const Retrieve = async function() {
const decrypt = await connection.testdata_connection.query("EXEC [SPROC] [INPUT]")
console.log(decrypt)
}
module.exports = {
tests: Tests(),
retrieve: Retrieve()
};
当我启动服务器时,这将使用正确的数据登录到我的控制台。当我用我的端点击中它时,我希望它这样做。
最佳答案
首先,您的函数应该被导出但不执行:
// creating an async function (all i/o operations should be async).
const Retrieve = async(testName) => connection.testdata_connection.query("EXEC [SPROC] [INPUTS]")
module.exports = {
retrieve: Retrieve,
// retrieve: Retrieve() if you call the function with (), the function will be executed and we don't want that yet
};
现在我们可以在路由中调用它:const query = require('./database/queries'); ///Imports sequelize queries
const app = express();
// the route is async because it is executing async code
app.get('/decrypt', async (req,res) => {
// waiting for the answer with await
const response = await query.retrieve();
// Doing something with the response
})
您仍然需要检查错误,但这是基础知识。
关于node.js - 使用 sequelize 和 express API 调用存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68026363/