lon*_*nix 2 mediator publish-subscribe cqrs node.js express
我是 Node/Express 的新手。我有一系列长期运行的流程,例如: post to Express endpoint -> save data (can return now) -> handle data -> handle data -> handle data -> another process -> etc.
一个典型的POST:
app.post("/foo", (req, res) => {
// save data and return
return res.send("200");
// but now I want to do a lot more stuff...
});
Run Code Online (Sandbox Code Playgroud)
如果我省略了return那么更多的处理将会发生,但即使我是这个堆栈的新手,我也可以说这是一个坏主意。
我想要的只是接收一些数据,保存并返回。然后我想开始处理它,并调用其他进程,调用其他进程等。我不希望原始 POST 等待所有这些完成。
我需要在进程中执行此操作,因此我无法保存到队列并在之后单独处理它。
基本上我想将数据的接收和处理分开,正在进行中。
使用 Node/Express 有哪些可用选项?
我会尝试这样的事情:
const express = require("express");
const port = 3000;
const app = express();
const uuid = require('uuid');
app.post("/foo", (req, res) => {
const requestId = uuid.v4();
// Send result. Set status to 202: The request has been accepted for processing, but the processing has not been completed. See https://tools.ietf.org/html/rfc7231#section-6.3.3.
res.status(202).json({ status: "Processing data..", requestId: requestId });
// Process request.
processRequest(requestId, request);
});
app.get("/fooStatus", (req, res) => {
// Check the status of the request.
let requestId = req.body.requestId;
});
function processRequest(requestId, request) {
/* Process request here, then perhaps save result to db. */
}
app.listen(port);
console.log(`Serving at http://localhost:${port}`);
Run Code Online (Sandbox Code Playgroud)
用 curl 调用它(例如):
curl -v -X POST http://localhost:3000/foo
Run Code Online (Sandbox Code Playgroud)
会给出如下响应:
{"status":"Processing data..","requestId":"abbf6a8e-675f-44c1-8cdd-82c500cbbb5e"}
Run Code Online (Sandbox Code Playgroud)