node.js - Controller 内的解雇和忘记 worker

标签 node.js

我需要创建一个简单的解决方案来接收用户的输入,查询我们的数据库并以任何方式返回结果,但查询可能需要长达半个小时的时间才能运行(并且我们的云配置为 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}.`)
})

查询.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/

相关文章:

node.js 与meteor.js 有什么区别?

javascript - 如何在不破坏链接的情况下替换部分网址?

mysql - 在 Node.js 中使用 mysql 和 Promise

javascript - 我如何找到称为 node.js 脚本的进程?

node.js - 如何解决尝试创建太多滚动上下文。必须小于或等于 : [500]?

node.js - Passport 加 express : serialization issue with custom authentication method

node.js - 使用 ECONNREFUSED 在本地连接到 DynamoDB 时出现问题

javascript - 从 JSON 比较中排除丢失的键

sql - 从 NodeJS Knex 插入到 Postgres 多维文本数组

node.js - 来自 Mongo Atlas 的配置限制的连接百分比已超过 80