Reputation: 1059
I want to have a variable that could keep its value from the last API call. That is, every time I call /api
, it increments a variable count by 1, and when I call /value
, it shows the value of count. So if I call /api
3 times and then call /value
, it should print 3.
Is it possible? To keep the value of the variable throw multiple API calls? I'm trying to avoid access files and databases, I'm sure I can do that with those.
Upvotes: 5
Views: 5049
Reputation:
You could create a module that you can require at any part of your app.
For example, you have a module in counter.js
defined as
var counter = function() {
var count = 0;
this.addCount = function() {
count++
}
this.getCount = function() {
return count;
}
}
counter.instance = null;
counter.getInstance = function() {
if (this.instance === null) {
this.instance = new counter();
}
return this.instance;
}
module.exports = counter.getInstance();
Now, you can use it in the server.js
like this
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var counter = require('./counter.js');
app.get('/value', function(req, res, next) {
res.send('Count = ' + counter.getCount());
});
app.use('/api', require('./api.js'));
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Server listening at http://%s:%s", host, port);
});
And in your api.js
like this
var express = require('express');
var router = express.Router();
var counter = require('./counter.js');
router.get('/', function(req, res, next) {
counter.addCount();
res.send('API Called');
});
module.exports = router;
Upvotes: 4
Reputation: 64
You can set a global variable like this outside of your api...
var count = 0;
Then make an api like this...
app.get('/value', function(req, res) {
res.send(count);
})
app.get('/api', function(req, res) {
count = count + 1;
res.send();
})
The above example is using the express framework. If you aren't use it, you should get used to it. It's a great framework!
Upvotes: 0
Reputation: 3683
If you create the variable in the top-level
of your js file it will be global for that js file. Also if your /api
and /value
route handlers are in diferent files you can create a global variable
that it will be visible in all your other files. But you have to take in count that no other variables should have the same name that your global variable, because it will be overwritted.
Here you have a good related post : How to use global variable in node.js?
var count = 0;
app.get('/api', function(req, res) {
count += 1;
res.send();
}
app.get('/value', function(req, res) {
res.send(count);
}
Upvotes: 7
Reputation: 54
Yes, Use can use express session or any other session for the same, or global variable
Upvotes: -1