Created
January 14, 2020 17:55
-
-
Save icai/78445b51d4de5c5839d35d1e4b5d16cb to your computer and use it in GitHub Desktop.
nuxt i18n middleware which don't need to format the nuxt-link url, hack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import LOCALES from '~/lang/locales' | |
| const debug = require('debug')('auth:server:i18n:middleware') | |
| const DEFAULT_LOCALE = 'en' | |
| export default function (context) { | |
| const { app, store, route, error, redirect, hotReload, from } = context; | |
| // Check if middleware called from hot-reloading, ignore | |
| if (hotReload) return | |
| // Get locale from params | |
| let locale = DEFAULT_LOCALE | |
| LOCALES.forEach(l => { | |
| const regexp = new RegExp(`^/${l.code}`) | |
| if (route.path.match(regexp)) { | |
| locale = l.code | |
| } | |
| }) | |
| // debug(locale, app.i18n.locale) | |
| if (LOCALES.findIndex(l => l.code === locale) === -1) { | |
| return error({ message: 'Page not found.', statusCode: 404 }) | |
| } | |
| const routePath = route.path | |
| if (locale === app.i18n.locale) { | |
| if (routePath.indexOf(`/${DEFAULT_LOCALE}`) === 0) { | |
| const regexp = new RegExp(`^/${DEFAULT_LOCALE}`) | |
| return redirect(route.fullPath.replace(regexp, '/')) | |
| } else { | |
| return; | |
| } | |
| } | |
| // /zh/register -> /register | |
| if (locale !== app.i18n.locale) { | |
| // If route is /<DEFAULT_LOCALE>/... -> redirect to /... | |
| if (locale === DEFAULT_LOCALE) { | |
| if (routePath.indexOf(`/${DEFAULT_LOCALE}`) === 0) { | |
| const regexp = new RegExp(`^/${DEFAULT_LOCALE}`) | |
| return redirect(route.fullPath.replace(regexp, '')) | |
| } else { | |
| // If route /LOCALE/xxxPage jump to /xxxPage | |
| if (from.name == route.name.replace(locale, app.i18n.locale)) { | |
| return; | |
| } else { | |
| // If route /LOCALE/xxxPage jump to /yyyPage -> redirect to /LOCALE/yyyPage | |
| // this hack the nuxt-link url | |
| return redirect({ path: `/${app.i18n.locale}${routePath}`, query: route.query }); | |
| } | |
| } | |
| } | |
| if (routePath.indexOf(`/${locale}`) === 0) { | |
| return; | |
| } else { | |
| return redirect({ path: `/${app.i18n.locale}${routePath}`, query: route.query }) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment