我需要创建一个简单的解决方案以接收来自用户的输入,查询我们的数据库并以任何方式返回结果,但是查询可能需要长达半个小时的时间才能运行(并且我们的云配置为在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}.`)
})
queries.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
}
答案 0 :(得分:1)
通过使用回调,并根据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
}
================================================ =============================
另一种方法可能是实现一个排队系统,该系统会将这些请求推送到队列,并让另一个进程侦听和发送电子邮件。不过那会有点复杂。