I have a very simple Node.js server (using Express.js) running locally on port 8000.
Using the npm package serialport
, I managed to connect to a scale and get its weight in a continuously mode like so.
Terminal output..
0
10
20
30
50
50 stable
50 stable
...
I want to save the scale stable weight to a database (in my case MongoDB Atlas), but I don't want to make hundreds of requests as the scale weight changes.
I know tools like RxJS
and one of its operators distictUntilChange
, but I'm not using any client.
How this can be done working only with a server?
Since you haven't shown any code, here's a conceptual answer, which assumes that your readings are coming from an async iterator and that you already have a function for uploading each weight value. In this example, the weight
property of each reading is a number
and the stable
property of each reading is a nullish boolean
.
async function uploadLoop (scaleReaderIterator, uploadWeight) {
let previousWeight;
for await (const {weight, stable} of scaleReaderIterator) {
if (
!stable || // the weight reading isn't stable, OR
weight === previousWeight // the weight hasn't changed since last time
) continue; // don't do anything else in this code block
// else
// update the previous value
previousWeight = weight;
// upload it
uploadWeight(weight);
} // loop
}