Background
I am making a Node.js app that generates a random number every 6 seconds, and makes it available via an API.
To keep the number generation logic out of the API file, I encapsulated in a function called numberGen
, in another file.
api.js
const express = require("express");
const numberFactory = require("../numberGen.js");
module.exports = (function() {
let interval = 6, min = 0, max = 100;
const api = express.Router();
const numberGen = numberFactory({
interval, min, max
});
numberGen.run();
api.get("/Numbers/", (req, res) => {
res.json({ random: numberGen.currNum});
});
return api;
})();
numberGen.js
"use strict";
module.exports = function(args) {
let {
interval,
min,
max
} = args;
let currNumber = genRandom(min, max);
function run() {
setTimeout(() => {
currNumber = genRandom(min, max);
run();
}, interval);
}
function genRandom(min, max){
return Math.floor(Math.random() * max) + min;
}
return {
interval, currNumber,
run
};
};
Ideally, a client make a request at 0 seconds, would get number X, and making the same request 6 seconds after, would get a number Y, as the server generates a new random number every 6 seconds.
Problem
The problem here is that the client always gets the same number, no matter what.
Tentatives
At first I thought this was happening because numberGen
is returning an object that never changes. To fix it, I tried passing a number from the api.js
to the generator to update, but it didn't work either as the client always gets an empty object, because serverNum === undefined
;
numberGen.js
"use strict";
module.exports = function(args) {
let {
interval,
min,
max,
serverNum
} = args;
serverNum = genRandom(min, max);
function run() {
setTimeout(() => {
serverNum= genRandom(min, max);
run();
}, interval);
}
function genRandom(min, max){
return Math.floor(Math.random() * max) + min;
}
return {
interval,
run
};
};
api.js
const express = require("express");
const numberFactory = require("../numberGen.js");
module.exports = (function() {
let interval = 6, min = 0, max = 100, serverNum;
const api = express.Router();
const numberGen = numberFactory({
interval, min, max, serverNum
});
numberGen.run();
api.get("/Numbers/", (req, res) => {
res.json({ random: serverNum});
});
return api;
})();
Question
Having in mind I want to keep this logic separated from the api.js
file, how can I fix my code?
via Flame_Phoenix
No comments:
Post a Comment