javascriptnode.jstotal.js

Total.js wait for event in localization


trying to wait for async call in total.js for localization. However, when I do try to make localization.js part wait for the response, program continues and selects language 'en' automatically. The code below is not taking care of async process, but I shared it to show what I am trying to do. Any idea how to do that?

var COOKIE = '__language',
allowed = {en: true, dk: true};

F.onLocate = function (req, res) {
var self = this,
language = req.query.language || req.cookie(COOKIE);
var userIP = self.ip

// Set the language according to the querystring and store to the cookie
if (language) {
    if (!allowed[language])
        return 'en';
    res.cookie(COOKIE, language, '2 days');
    return language;
}

// addition if cookie is not set, first time Danish users will have 'dk' cookie set
else {
 // return from here works
   Util.waitUtils.request('https://ipfind.co?ip='+userIP +'&auth=myauthcodehere'
    , ['get'], function(err, data, status, headers) {


          var result = JSON.parse(data);

          if(result.country_code === 'DK')
            {
              res.redirect('/?language=dk');

             }
 });
}

res.cookie(COOKIE, 'en', '2 days');
return 'en';
};

Solution

  • this is not possible. F.onLocale is synchronous. Solution is to use a middleware:

    F.middleware('language', function(req, res, next) {
    
        // ...
        // ...
    
        RESTBuilder.make(function(builder) {
            builder.url('https://ipfind.com?ip={0}&myauthcodehere={1}'.format(req.ip, 'myauthcodehere'));
            builder.exec(function(err, response) {
    
                req.language = response.country_code;
                next();
    
                // or
                // res.redirect('?language=dk');
                // next = null;
            });
        });
    });
    

    Thank you.