Skip to content

Commit

Permalink
fix: change default-locale-redirect to middleware
Browse files Browse the repository at this point in the history
fix: getLocalizedRoute with locale
add: tests
  • Loading branch information
s00d committed Aug 17, 2024
1 parent e34df41 commit b4defbf
Show file tree
Hide file tree
Showing 21 changed files with 314 additions and 76 deletions.
48 changes: 48 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: ci

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
lint:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- run: corepack enable
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Install dependencies
run: npx nypm@latest i

- name: Lint
run: npm run lint

test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- run: corepack enable
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Install dependencies
run: npx nypm@latest i

- name: Install playwright
run: npx playwright install

- name: Playground prepare
run: npm run dev:prepare

- name: Test
run: npm run test
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ coverage
.nyc_output

# VSCode
.vscode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
Expand All @@ -54,3 +55,4 @@ coverage
Network Trash Folder
Temporary Items
.apdisk
test-results
64 changes: 62 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"release": "npm run lint && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"test": "vitest run",
"test": "playwright test",
"test:watch": "vitest watch",
"test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit",
"client:build": "nuxi generate client",
Expand All @@ -67,11 +67,12 @@
"@nuxt/module-builder": "^0.8.3",
"@nuxt/schema": "^3.12.4",
"@nuxt/test-utils": "^3.14.1",
"@playwright/test": "^1.46.1",
"@types/node": "^20.14.11",
"changelogen": "^0.5.5",
"eslint": "^9.7.0",
"nuxt": "^3.12.4",
"execa": "^9.3.0",
"nuxt": "^3.12.4",
"typescript": "latest",
"vitest": "^2.0.3",
"vue-tsc": "^2.0.26"
Expand Down
1 change: 1 addition & 0 deletions playground/locales/pages/subpage/de.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions playground/locales/pages/subpage/en.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions playground/locales/pages/subpage/ru.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
4 changes: 3 additions & 1 deletion playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
"scripts": {
"dev": "nuxi dev",
"build": "nuxi build",
"prepare": "nuxt prepare",
"generate": "nuxi generate"
},
"dependencies": {
"nuxt": "^3.12.4"
"nuxt": "^3.12.4",
"nuxt-i18n-micro": "^1.1.1"
}
}
5 changes: 5 additions & 0 deletions playground/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@
</button>
</div>

<p id="localized-route">
{{ $localeRoute({ name: 'page' }, 'de').path }}
</p>

<div>
<NuxtLink :to="$localeRoute({ name: 'page' })">
Go to Page
</NuxtLink>
</div>
<a href="/">test</a>

<div
v-for="key in generatedKeys"
Expand Down
25 changes: 21 additions & 4 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import path from 'node:path'
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
import { addPlugin, addTypeTemplate, createResolver, defineNuxtModule, extendPages } from '@nuxt/kit'
import { addPlugin, addServerHandler, addTypeTemplate, createResolver, defineNuxtModule, extendPages } from '@nuxt/kit'
import type { HookResult } from '@nuxt/schema'
import { setupDevToolsUI } from './devtools'

Expand Down Expand Up @@ -97,9 +97,9 @@ export default defineNuxtModule<ModuleOptions>({
}

if (options.includeDefaultLocaleRoute) {
addPlugin({
src: resolver.resolve('./runtime/05.default-locale-redirect'),
order: 4,
addServerHandler({
middleware: true,
handler: resolver.resolve('./runtime/server/middleware/i18n-redirect.ts'),
})
}

Expand Down Expand Up @@ -216,6 +216,23 @@ export default defineNuxtModule<ModuleOptions>({
}
}
declare module 'vue/types/vue' {
interface Vue {
$getLocale: () => string;
$getLocales: () => string[];
$t: <T extends Record<string, string | number | boolean>>(
key: string,
params?: T,
defaultValue?: string
) => string | number | boolean | Translations | PluralTranslations | unknown[] | unknown | null;
$tc: (key: string, count: number, defaultValue?: string) => string;
$mergeTranslations: (newTranslations: Translations) => void;
$switchLocale: (locale: string) => void;
$localeRoute: (to: RouteLocationRaw, locale?: string) => RouteLocationRaw;
$loadPageTranslations: (locale: string, routeName: string) => Promise<void>;
}
}
export {};
`
},
Expand Down
22 changes: 8 additions & 14 deletions src/runtime/01.plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,24 +144,18 @@ function getLocalizedRoute(to: RouteLocationRaw, router: Router, route: RouteLoc
const { defaultLocale } = i18nConfig
const currentLocale = (locale || route.params.locale || defaultLocale)!.toString()

let resolvedRoute = router.resolve(to)
const selectRoute = router.resolve(to)

if (typeof to === 'object' && 'name' in to) {
resolvedRoute = router.resolve({ name: to.name, params: to.params, query: to.query, hash: to.hash })
delete resolvedRoute.params.locale

if (resolvedRoute.name) {
const routeName = (resolvedRoute.name as string).replace(`localized-`, '')

resolvedRoute.name = currentLocale !== defaultLocale || i18nConfig.includeDefaultLocaleRoute ? `localized-${routeName}` : routeName
const routeName = (selectRoute.name as string).replace(`localized-`, '')
const newRouteName = currentLocale !== defaultLocale || i18nConfig.includeDefaultLocaleRoute ? `localized-${routeName}` : routeName
const newParams = { ...route.params }
delete newParams.locale

if (defaultLocale !== currentLocale || i18nConfig.includeDefaultLocaleRoute) {
resolvedRoute.params.locale = currentLocale
}
}
if (currentLocale !== defaultLocale || i18nConfig.includeDefaultLocaleRoute) {
newParams.locale = currentLocale
}

return resolvedRoute
return router.resolve({ name: newRouteName, params: newParams })
}

export default defineNuxtPlugin(async (_nuxtApp) => {
Expand Down
40 changes: 0 additions & 40 deletions src/runtime/05.default-locale-redirect.ts

This file was deleted.

29 changes: 29 additions & 0 deletions src/runtime/server/middleware/i18n-redirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { defineEventHandler, sendRedirect } from 'h3'
import type { H3Event } from 'h3'
import type { Locale } from 'nuxt-i18n-micro'
import type { ModuleOptions } from '~/src/module'
import { useRuntimeConfig } from '#imports'

export default defineEventHandler(async (event: H3Event) => {
const config = useRuntimeConfig()
const i18nConfig = config.public.i18nConfig as ModuleOptions

// Ensure defaultLocale is defined
if (!i18nConfig.defaultLocale) {
throw new Error('defaultLocale is not defined in the module configuration')
}

const locales = i18nConfig.locales || []

const pathParts = event.path.split('/').filter(Boolean)
const localeCode = pathParts[0]
// If the locale is missing or invalid, redirect to the route with the defaultLocale
const locale = locales.find((loc: Locale) => loc.code === localeCode)

// If the locale is missing or invalid, redirect to the route with the defaultLocale
if (!locale) {
const newPath = `/${i18nConfig.defaultLocale}/${pathParts.join('/')}`

return sendRedirect(event, newPath, 301)
}
})
Loading

0 comments on commit b4defbf

Please sign in to comment.