我已经使用Node和ExpressJS开发了REST-API,我需要创建一个临时缓冲区来比较X秒钟内请求接收的数据。
例如,服务器接收一个请求,将其存储在缓冲区中并启动计时器。当计时器没有完成时,所有请求数据也将存储在该缓冲区中。计时器结束后,我需要比较缓冲区内的所有数据,然后将其发送到数据库。
我的问题是我不知道是否可以使用node和express来实现,但我没有找到任何可能的解决方案。也许有人可以帮助我解决我的问题。谢谢。
答案 0 :(得分:1)
我确定有可以执行此操作的库,但是如果您想自己实现它,可以执行以下操作:
您可以编写一个小的Request-Recorder类,该类公开一个recordData
方法,如果记录器当前处于活动状态或尚未记录任何数据,则该方法可以记录请求数据。如果后一种情况成立,则启用计时器并使其记录数据,直到达到超时为止。这样的事情应该可以帮助您入门:
class RequestDataRecorder {
static instance;
constructor() {
this.isActive = false;
this.isLocked = false;
// could also be a map, holding request data by request-id for example
this.recordedData = [];
this.recordDataDurationInSeconds = 10; // will capture request data within 10 second time frames
}
static shared() {
if (!RequestDataRecorder.instance) {
RequestDataRecorder.instance = new RequestDataRecorder();
}
return RequestDataRecorder.instance;
}
recordData(data) {
if (this.canActivate()) {
this.activate();
}
if (this.isCurrentlyActive()) {
this.recordedData.push(data);
}
}
canActivate() {
return !this.isLocked && !this.isActive && this.recordedData.length === 0;
}
activate() {
this.isLocked = true;
this.timer = setTimeout(() => {
this.deactivate();
this.exportData();
}, this.recordDataDurationInSeconds * 1000);
this.isLocked = false;
this.setActive(true);
}
deactivate() {
this.isLocked = true;
this.setActive(false);
clearTimeout(this.timer);
this.recordedData = [];
this.isLocked = false;
}
setActive(val) {
this.isActive = val;
}
isCurrentlyActive() {
return this.isActive;
}
exportData() {
// do your db-export here or use another class to to the export with this data (preferably the latter to comply with the single-responsibilty principle :))
return this.recordedData;
}
}
您可以像这样使用此类:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const requestDataRecorder = RequestDataRecorder.shared();
app.post("/postSomeData", (req, res) => {
requestDataRecorder.recordData(req.body);
res.status(201).end();
});
app.get("/getRecordedData", (req, res) => {
res.send(requestDataRecorder.getRecordedData());
});
app.listen(3000, function () {
console.log("Server is listening!");
});