Skip to content

Commit

Permalink
feat: Add beforeLanguageSwitch & onLanguageSwitched callbacks
Browse files Browse the repository at this point in the history
Provides 2 callback called by the middleware when a language change is detected.
beforeLanguageSwitch is called right before setting the new locale, onLanguageSwitched is called
once the locale is set.
  • Loading branch information
paulgv committed Mar 14, 2018
1 parent c2e65e5 commit 21b5f13
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ module.exports = function (moduleOptions) {
ignorePaths: [],
detectBrowserLanguage: false,
redirectCookieKey: 'redirected',
useRedirectCookie: true
useRedirectCookie: true,
beforeLanguageSwitch: (oldLocale, newLocale) => {},
onLanguageSwitched: (oldLocale, newLocale) => {}
}
const options = merge(defaults, moduleOptions, this.options.i18n)

Expand Down
2 changes: 2 additions & 0 deletions lib/templates/i18n.plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export default ({ app, route, error }) => {
app.i18n.locales = <%= JSON.stringify(options.locales) %>
app.i18n.defaultLocale = '<%= options.defaultLocale %>'
app.i18n.ignorePaths = <%= JSON.stringify(options.ignorePaths) %>
app.i18n.beforeLanguageSwitch = <%= options.beforeLanguageSwitch %>
app.i18n.onLanguageSwitched = <%= options.onLanguageSwitched %>

// Get locale from params
let locale = app.i18n.defaultLocale || null
Expand Down
4 changes: 4 additions & 0 deletions lib/templates/i18n.routing.middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,17 @@ middleware['i18n'] = function ({ app, req, res, route, params, redirect, error,
return error({ message: 'Page not found.', statusCode: 404 })
}
if (locale === app.i18n.locale) return
const oldLocale = app.i18n.locale
app.i18n.beforeLanguageSwitch(oldLocale, locale)
if (<%= options.loadLanguagesAsync %>) {
const { loadLanguageAsync } = require('./i18n.utils')
loadLanguageAsync(app.i18n, locale)
.then(() => {
app.i18n.locale = locale
app.i18n.onLanguageSwitched(oldLocale, locale)
})
} else {
app.i18n.locale = locale
app.i18n.onLanguageSwitched(oldLocale, locale)
}
}

0 comments on commit 21b5f13

Please sign in to comment.