我需要创建一个简单的解决方案来接收用户的输入,以任何方式查询我们的数据库并返回结果,但是查询可能要花费半个小时才能运行(并且我们的云配置为在2分钟后超时,我不允许更改它)。
我提出了以下在本地工作的解决方案,并希望包含代码以通过电子邮件将查询的结果发送给用户(即发即忘),但是不确定如何在将HTTP 200返回给用户时执行该操作。
index.js:
const express = require('express')
const bodyParser = require('body-parser')
const db = require('./queries')
const app = express()
const port = 3000
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.get('/', (request, response) => {
response.json({ info: 'Node.js, Express, and Postgres API' })
})
app.post('/report', db.getReport)
app.get('/test', db.getTest)
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
querys.js:
const Pool = require('pg').Pool
const pool = new Pool({
user: 'xxx',
host: 'xx.xxx.xx.xxx',
database: 'xxxxxxxx',
password: 'xxxxxxxx',
port: xxxx,
})
const getReport = (request, response) => {
const { business_group_id, initial_date, final_date } = request.body
pool.query(` SELECT GIANT QUERY`, [business_group_id, initial_date, final_date], (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
// I want to change that to something like:
// FireNForgetWorker(params)
// response.status(200)
}
module.exports = {
getReport
}
最佳答案
通过使用回调,并基于express的设计,您可以发送响应并继续执行同一功能。因此,您可以将其重组为如下所示:
const Pool = require('pg').Pool
const pool = new Pool({
user: 'xxx',
host: 'xx.xxx.xx.xxx',
database: 'xxxxxxxx',
password: 'xxxxxxxx',
port: xxxx,
})
const getReport = (request, response) => {
const { business_group_id, initial_date, final_date } = request.body
pool.query(` SELECT GIANT QUERY`, [business_group_id, initial_date, final_date], (error, results) => {
if (error) {
// TODO: Do something to handle error, or send an email that the query was unsucessfull
throw error
}
// Send the email here.
})
response.status(200).json({message: 'Process Began'});
}
module.exports = {
getReport
}
================================================== ==========================
另一种方法可能是实现一个排队系统,该系统会将这些请求推送到队列,并让另一个进程监听和发送电子邮件。但是,那将更加复杂。
关于node.js - Controller 内的解雇 worker ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54905943/