Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/h3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"prepack": "pnpm build"
},
"dependencies": {
"@intlify/core": "^11.1.12",
"@intlify/core": "catalog:",
"@intlify/utils": "catalog:"
},
"devDependencies": {
Expand Down
7 changes: 4 additions & 3 deletions packages/h3/spec/integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ test('translation', async () => {
})

describe('custom locale detection', () => {
test('basic', async () => {
test('basic detection', async () => {
// define custom locale detector
const localeDetector = (event: H3Event): string => {
return getQueryLocale(event.req).toString()
Expand Down Expand Up @@ -88,7 +88,7 @@ describe('custom locale detection', () => {
expect(body).toEqual({ message: 'こんにちは, h3' })
})

test('async', async () => {
test('detect with async loading', async () => {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

const loader = (path: string) => import(path).then(m => m.default || m)
Expand Down Expand Up @@ -150,7 +150,8 @@ describe('custom locale detection', () => {
expect(body).toEqual(translated[locale])
}
})
test('async parallel', async () => {

test('detect with async parallel loading', async () => {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

const loader = (path: string) => import(path).then(m => m.default || m)
Expand Down
60 changes: 54 additions & 6 deletions packages/hono/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,9 @@ const app = new Hono()
// install middleware with `app.use`
app.use('*', i18nMiddleware)

app.get('/', c => {
app.get('/', async c => {
// use `useTranslation` in handler
const t = useTranslation(c)
const t = await useTranslation(c)
return c.text(t('hello', { name: 'hono' }) + `\n`)
})

Expand Down Expand Up @@ -139,6 +139,54 @@ const middleware = defineI18nMiddleware({
})
```

You can make that function asynchronous. This is useful when loading resources along with locale detection.

<!-- eslint-disable markdown/no-missing-label-refs -- NOTE(kazupon): ignore github alert -->

> [!NOTE]
> The case which a synchronous function returns a promise is not supported. you need to use `async function`.

<!-- eslint-enable markdown/no-missing-label-refs -- NOTE(kazupon): ignore github alert -->

```ts
import { Hono } from 'hono'
import { defineI18nMiddleware, getCookieLocale } from '@intlify/hono'

import type { Context } from 'hono'
import type { DefineLocaleMessage, CoreContext } from '@intlify/h3'

const loader = (path: string) => import(path).then(m => m.default)
const messages: Record<string, () => ReturnType<typeof loader>> = {
en: () => loader('./locales/en.json'),
ja: () => loader('./locales/ja.json')
}

// define custom locale detector and lazy loading
const localeDetector = async (
ctx: Context,
i18n: CoreContext<string, DefineLocaleMessage>
): Promise<string> => {
// detect locale
const locale = getCookieLocale(ctx.req.raw).toString()

// resource lazy loading
const loader = messages[locale]
if (loader && !i18n.messages[locale]) {
const message = await loader()
i18n.messages[locale] = message
}

return locale
}

const middleware = defineI18nMiddleware({
// set your custom locale detector
locale: localeDetector
// something options
// ...
})
```

## 🧩 Type-safe resources

<!-- eslint-disable markdown/no-missing-label-refs -- NOTE(kazupon): ignore github alert -->
Expand Down Expand Up @@ -234,12 +282,12 @@ You can `useTranslation` set the type parameter to the resource schema you want
the part of example:

```ts
app.get('/', c => {
app.get('/', async c => {
type ResourceSchema = {
hello: string
}
// set resource schema as type parameter
const t = useTranslation<ResourceSchema>(c)
const t = await useTranslation<ResourceSchema>(c)
// you can completion when you type `t('`
return c.json(t('hello', { name: 'hono' }))
})
Expand Down Expand Up @@ -270,8 +318,8 @@ declare module '@intlify/hono' {
export interface DefineLocaleMessage extends ResourceSchema {}
}

app.get('/', c => {
const t = useTranslation(c)
app.get('/', async c => {
const t = await useTranslation(c)
// you can completion when you type `t('`
return c.json(t('hello', { name: 'hono' }))
})
Expand Down
2 changes: 1 addition & 1 deletion packages/hono/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
"prepack": "pnpm build"
},
"dependencies": {
"@intlify/core": "^11.0.0",
"@intlify/core": "catalog:",
"@intlify/utils": "catalog:"
},
"devDependencies": {
Expand Down
4 changes: 2 additions & 2 deletions packages/hono/playground/basic/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ const i18n = defineI18nMiddleware({

const app: Hono = new Hono()
app.use('*', i18n)
app.get('/', c => {
const t = useTranslation(c)
app.get('/', async c => {
const t = await useTranslation(c)
return c.text(t('hello', { name: 'hono' }) + `\n`)
})

Expand Down
4 changes: 2 additions & 2 deletions packages/hono/playground/global-schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ const i18n = defineI18nMiddleware({

const app: Hono = new Hono()
app.use('*', i18n)
app.get('/', c => {
const t = useTranslation(c)
app.get('/', async c => {
const t = await useTranslation(c)
return c.text(t('hello', { name: 'hono' }))
})

Expand Down
4 changes: 2 additions & 2 deletions packages/hono/playground/local-schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ const i18n = defineI18nMiddleware({

const app: Hono = new Hono()
app.use('*', i18n)
app.get('/', c => {
app.get('/', async c => {
type ResourceSchema = {
hello: string
}
const t = useTranslation<ResourceSchema>(c)
const t = await useTranslation<ResourceSchema>(c)
return c.text(t('hello', { name: 'hono' }))
})

Expand Down
2 changes: 1 addition & 1 deletion packages/hono/spec/e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,6 @@ describe('e2e', () => {
const stdout = await runCommand(
`curl -H 'Accept-Language: ja,en-US;q=0.7,en;q=0.3' http://localhost:3000`
)
expect(stdout).toContain(`こんにちは, h3`)
expect(stdout).toContain(`こんにちは, hono`)
})
})
3 changes: 3 additions & 0 deletions packages/hono/spec/fixtures/en.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"hello": "hello, {name}"
}
3 changes: 3 additions & 0 deletions packages/hono/spec/fixtures/ja.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"hello": "こんにちは, {name}"
}
168 changes: 143 additions & 25 deletions packages/hono/spec/integration.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { Hono } from 'hono'
import { afterEach, expect, test, vi } from 'vitest'
import { afterEach, describe, expect, test, vi } from 'vitest'
import {
defineI18nMiddleware,
detectLocaleFromAcceptLanguageHeader,
getQueryLocale,
useTranslation
} from '../src/index.ts'

import type { CoreContext } from '@intlify/core'
import type { Context } from 'hono'
import type { DefineLocaleMessage } from '../src/index.ts'

let app: Hono

Expand All @@ -29,8 +31,8 @@ test('translation', async () => {
})
app = new Hono()
app.use('*', i18nMiddleware)
app.get('/', c => {
const t = useTranslation(c)
app.get('/', async c => {
const t = await useTranslation(c)
return c.json({ message: t('hello', { name: 'hono' }) })
})

Expand All @@ -42,36 +44,152 @@ test('translation', async () => {
expect(await res.json()).toEqual({ message: 'hello, hono' })
})

test('custom locale detection', async () => {
const defaultLocale = 'en'
describe('custom locale detection', () => {
test('basic detection', async () => {
const defaultLocale = 'en'

// define custom locale detector
const localeDetector = (ctx: Context): string => {
try {
return getQueryLocale(ctx.req.raw).toString()
} catch {
return defaultLocale
// define custom locale detector
const localeDetector = (ctx: Context): string => {
try {
return getQueryLocale(ctx.req.raw).toString()
} catch {
return defaultLocale
}
}
}

const i18nMiddleware = defineI18nMiddleware({
locale: localeDetector,
messages: {
const i18nMiddleware = defineI18nMiddleware({
locale: localeDetector,
messages: {
en: {
hello: 'hello, {name}'
},
ja: {
hello: 'こんにちは, {name}'
}
}
})
app = new Hono()
app.use('*', i18nMiddleware)
app.get('/', async c => {
const t = await useTranslation(c)
return c.json({ message: t('hello', { name: 'hono' }) })
})

const res = await app.request('/?locale=ja')
expect(await res.json()).toEqual({ message: 'こんにちは, hono' })
})

test('detect with async loading', async () => {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

const loader = (path: string) => import(path).then(m => m.default || m)
const messages: Record<string, () => ReturnType<typeof loader>> = {
en: () => loader('./fixtures/en.json'),
ja: () => loader('./fixtures/ja.json')
}

// async locale detector
const localeDetector = async (ctx: Context, i18n: CoreContext<string, DefineLocaleMessage>) => {
const locale = getQueryLocale(ctx.req.raw).toString()
await sleep(100)
const loader = messages[locale]
if (loader && !i18n.messages[locale]) {
const message = await loader()
i18n.messages[locale] = message
}
return locale
}

const i18nMiddleware = defineI18nMiddleware({
locale: localeDetector,
messages: {
en: {
hello: 'hello, {name}'
},
ja: {
hello: 'こんにちは, {name}'
}
}
})

app = new Hono()
app.use('*', i18nMiddleware)
app.get('/', async c => {
const t = await useTranslation(c)
return c.json({ message: t('hello', { name: 'hono' }) })
})

const translated: Record<string, { message: string }> = {
en: {
hello: 'hello, {name}'
message: 'hello, hono'
},
ja: {
hello: 'こんにちは, {name}'
message: 'こんにちは, hono'
}
}

for (const locale of ['en', 'ja']) {
const res = await app.request(`/?locale=${locale}`)
expect(await res.json()).toEqual(translated[locale])
}
})
app = new Hono()
app.use('*', i18nMiddleware)
app.get('/', c => {
const t = useTranslation(c)
return c.json({ message: t('hello', { name: 'hono' }) })
})

const res = await app.request('/?locale=ja')
expect(await res.json()).toEqual({ message: 'こんにちは, hono' })
test('detect with async parallel loading', async () => {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

const loader = (path: string) => import(path).then(m => m.default || m)
const messages: Record<string, () => ReturnType<typeof loader>> = {
en: () => loader('./fixtures/en.json'),
ja: () => loader('./fixtures/ja.json')
}

// async locale detector
const localeDetector = async (ctx: Context, i18n: CoreContext<string, DefineLocaleMessage>) => {
const locale = getQueryLocale(ctx.req.raw).toString()
await sleep(100)
const loader = messages[locale]
if (loader && !i18n.messages[locale]) {
const message = await loader()
i18n.messages[locale] = message
}
return locale
}

const i18nMiddleware = defineI18nMiddleware({
locale: localeDetector,
messages: {
en: {
hello: 'hello, {name}'
}
}
})

app = new Hono()
app.use('*', i18nMiddleware)
app.use('/', async c => {
await sleep(100)
const t = await useTranslation(c)
await sleep(100)
return c.json({ message: t('hello', { name: 'hono' }) })
})

const translated: Record<string, { message: string }> = {
en: {
message: 'hello, hono'
},
ja: {
message: 'こんにちは, hono'
}
}
// request in parallel
const resList = await Promise.all(
['en', 'ja'].map(locale =>
app
.request(`/?locale=${locale}`)
// @ts-ignore
.then(res => res.json())
)
)
expect(resList).toEqual([translated['en'], translated['ja']])
})
})
Loading
Loading