Sailsjs req.setLocale outside controller

2019-07-27 05:40发布

问题:

I want to set the locale to other language than the default one, in cronjob scheduler. https://github.com/ghaiklor/sails-hook-cron

The cronjob scheduler code looks like that:

// ['seconds', 'minutes', 'hours', 'dayOfMonth', 'month', 'dayOfWeek']
module.exports.cron = {
  job: {
    schedule: '0 0 12 * * *',
    onTick: function() {
      SomeService.sendSms()
    },
    timezone: 'Asia/Jerusalem'
  }
}

But I cant set the locale because its not a controller but a service and I don't have access to req.setLocale globally.

回答1:

This depends on which version of Sails you're using.

For Sails v0.12.x, the only way to specify a locale dynamically is by using a dictionary as the argument to sails.__:

sails.__({ phrase: 'Welcome', locale: 'fr' })

will give you Bienvenue with a default Sails app.

This syntax isn't available in Sails 1.0, but you can change the current locale with sails.hooks.i18n.setLocale():

var curLocale = sails.hooks.i18n.getLocale();
sails.hooks.i18n.setLocale('fr');
sails.__('Welcome');
sails.hooks.i18n.setLocale(curLocale);

will again give you Bienvenue with a default Sails app, while ensuring that the locale is set back to the default afterwards. This way you don't accidentally change the locale for all subsequent invocations of __.