Geolocation in Total.js
- this tutorial uses a middleware
- obtained data will be stored in
req.geolocation
variable
- this tutorial extends
Controller
by adding geolocation()
method which returns req.geolocation
Create a definition file e.g. geolocation.js
:
// Temporary cache
var CACHE = {};
F.middleware('geolocation', function(req, res, next) {
if (CACHE[req.ip] !== undefined) {
req.geolocation = CACHE[req.ip];
next();
return;
}
var builder = new RESTBuilder();
builder.url('https://freegeoip.net/json/' + req.ip);
builder.get();
builder.exec(function(err, response) {
CACHE[req.ip] = req.geolocation = err ? null : response;
next();
});
});
Controller.prototype.geolocation = function() {
return this.req.geolocation;
};
// Clears cache every 10 minutes
F.on('service', function(counter) {
if (counter % 10 === 0)
CACHE = {};
});
Usage
Now we extend routes where we want to use Geolocation.
exports.install = function() {
F.route('/', view_index, ['#geolocation']);
};
function view_homepage() {
console.log(this.geolocation());
// or
console.log(this.req.geolocation);
this.view('index');
}
Result:
{ ip: '62.168.127.195',
country_code: 'SK',
country_name: 'Slovak Republic',
region_code: '',
region_name: '',
city: '',
zip_code: '',
time_zone: 'Europe/Bratislava',
latitude: 48.6667,
longitude: 19.5,
metro_code: 0 }
Tips
- we can use a global middleware via
F.use('geolocation', '*', ['web']);
- we can store geolocation data in cookies or in a database