Skip to content

Commit

Permalink
fix: fallback when cookie is wrong
Browse files Browse the repository at this point in the history
  • Loading branch information
Teages committed Jan 2, 2024
1 parent 7dbe97e commit 103eb98
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
},
"dependencies": {
"@nuxt/kit": "^3.9.0",
"destr": "^2.0.2",
"glob": "^10.3.10",
"knitwork": "^1.0.0",
"pathe": "^1.1.1",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

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

11 changes: 10 additions & 1 deletion src/runtime/composables/internal.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { LocaleCode } from "#build/locales/lazy-import"
import { available } from '#build/locales/available'
import { computed, useCookie, useState } from "#imports"
import destr from "destr"

export function useLocalesInternal() {
const _locales: Array<{ name: string, code: LocaleCode }> = available as any
Expand All @@ -23,8 +24,16 @@ export function useLocalesInternal() {
}
return null
})
const userPrefer = useCookie<LocaleCode>('locale', {
const userPrefer = useCookie<LocaleCode | null>('locale', {
maxAge: 35_600 * 24 * 60 * 60, // forever
decode: val => {
const parsed = destr<string>(decodeURIComponent(val))
if (_locales.find(l => l.code === parsed)) {
return parsed as LocaleCode
}
return null
},
encode: val => encodeURIComponent(typeof val === 'string' ? val : JSON.stringify(val)),
})
const locales = computed(() => _locales)

Expand Down
10 changes: 10 additions & 0 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@ describe('Basic', async () => {
})
check(html, 'ja-JP')
})

it('with accept-language and wrong cookie', async () => {
const html = await $fetch('/', {
headers: {
'Accept-Language': 'zh-CN',
Cookie: 'locale=ha-CK',
},
})
check(html, 'zh-CN')
})
})

function check(html: string, locale: string) {
Expand Down

0 comments on commit 103eb98

Please sign in to comment.