Coder Social home page Coder Social logo

hono's Introduction

@intlify/hono

npm version npm downloads CI

Internationalization middleware & utilities for Hono

๐ŸŒŸ Features

โœ…๏ธ ย Translation: Simple API like vue-i18n

โœ… ย Custom locale detector: You can implement your own locale detector on server-side

โœ…๏ธ๏ธ ย Useful utilities: support internationalization composables utilities via @intlify/utils

๐Ÿ’ฟ Installation

# Using npm
npm install @intlify/hono

# Using yarn
yarn add @intlify/hono

# Using pnpm
pnpm add @intlify/hono

# Using bun
bun add @intlify/hono

๐Ÿš€ Usage

import { Hono } from 'hono'
import {
  defineI18nMiddleware,
  detectLocaleFromAcceptLanguageHeader,
  useTranslation,
} from '@intlify/hono'

// define middleware with vue-i18n like options
const i18nMiddleware = defineI18nMiddleware({
  // detect locale with `accept-language` header
  locale: detectLocaleFromAcceptLanguageHeader,
  // resource messages
  messages: {
    en: {
      hello: 'Hello {name}!',
    },
    ja: {
      hello: 'ใ“ใ‚“ใซใกใฏใ€{name}๏ผ',
    },
  },
  // something options
  // ...
})

const app = new Hono()

// install middleware with `app.use`
app.use('*', i18nMiddleware)

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

export default app

๐Ÿ› ๏ธ Custom locale detection

You can detect locale with your custom logic from current Context.

example for detecting locale from url query:

import { defineI18nMiddleware, getQueryLocale } from '@intlify/hono'
import type { Context } from 'hono'

const DEFAULT_LOCALE = 'en'

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

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

๐Ÿงฉ Type-safe resources

Warning

This is experimental feature (inspired from vue-i18n). We would like to get feedback from you ๐Ÿ™‚.

Note

The exeample code is here

You can support the type-safe resources with schema using TypeScript on defineI18nMiddleware options.

Locale messages resource:

export default {
  hello: 'hello, {name}!'
}

your application code:

import { defineI18nMiddleware } from '@intlify/hono'
import en from './locales/en.ts'

// define resource schema, as 'en' is master resource schema
type ResourceSchema = typeof en

const i18nMiddleware = defineI18nMiddleware<[ResourceSchema], 'en' | 'ja'>({
  messages: {
    en: { hello: 'Hello, {name}' },
  },
  // something options
  // ...
})

// someting your implementation code ...
// ...

Result of type checking with tsc:

npx tsc --noEmit
index.ts:13:3 - error TS2741: Property 'ja' is missing in type '{ en: { hello: string; }; }' but required in type '{ en: ResourceSchema; ja: ResourceSchema; }'.

13   messages: {
     ~~~~~~~~

  ../../node_modules/@intlify/core/node_modules/@intlify/core-base/dist/core-base.d.ts:125:5
    125     messages?: {
            ~~~~~~~~
    The expected type comes from property 'messages' which is declared here on type 'CoreOptions<string, { message: ResourceSchema; datetime: DateTimeFormat; number: NumberFormat; }, { messages: "en"; datetimeFormats: "en"; numberFormats: "en"; } | { ...; }, ... 8 more ..., NumberFormats<...>>'


Found 1 error in index.ts:13

If you are using Visual Studio Code as an editor, you can notice that there is a resource definition omission in the editor with the following error before you run the typescript compilation.

Type-safe resources

๐Ÿ–Œ๏ธ Resource keys completion

Warning

This is experimental feature (inspired from vue-i18n). We would like to get feedback from you ๐Ÿ™‚.

Note

Resource Keys completion can be used if you are using Visual Studio Code

You can completion resources key on translation function with useTranslation.

Key Completion

resource keys completion has twe ways.

Type parameter for useTranslation

Note

The exeample code is here

You can useTranslation set the type parameter to the resource schema you want to key completion of the translation function.

the part of example:

app.get('/', c => {
  type ResourceSchema = {
    hello: string
  }
  // set resource schema as type parameter
  const t = useTranslation<ResourceSchema>(c)
  // you can completion when you type `t('`
  return c.json(t('hello', { name: 'hono' }))
}),

global resource schema with declare module '@intlify/hono'

Note

The exeample code is here

You can do resource key completion with the translation function using the typescript declare module.

the part of example:

import en from './locales/en.ts'

// 'en' resource is master schema
type ResourceSchema = typeof en

// you can put the type extending with `declare module` as global resource schema
declare module '@intlify/hono' {
  // extend `DefineLocaleMessage` with `ResourceSchema`
  export interface DefineLocaleMessage extends ResourceSchema {}
}

app.get('/', c => {
  const t = useTranslation(c)
  // you can completion when you type `t('`
  return c.json(t('hello', { name: 'hono' }))
}),

The advantage of this way is that it is not necessary to specify the resource schema in the useTranslation type parameter.

๐Ÿ› ๏ธ Utilites & Helpers

@intlify/hono has a concept of composable utilities & helpers.

Utilities

@intlify/hono composable utilities accept context (from (context) => {})) as their first argument. (Exclud useTranslation) return the Intl.Locale

Translations

  • useTranslation(context): use translation function

Headers

  • getHeaderLocale(context, options): get locale from accept-language header
  • getHeaderLocales(context, options): get some locales from accept-language header

Cookies

  • getCookieLocale(context, options): get locale from cookie
  • setCookieLocale(context, options): set locale to cookie

Misc

  • getPathLocale(context, options): get locale from path
  • getQueryLocale(context, options): get locale from query

Helpers

  • detectLocaleFromAcceptLanguageHeader(context): detect locale from accept-language header

๐Ÿ™Œ Contributing guidelines

If you are interested in contributing to @intlify/hono, I highly recommend checking out the contributing guidelines here. You'll find all the relevant information such as how to make a PR, how to setup development) etc., there.

ยฉ๏ธ License

MIT

hono's People

Contributors

kazupon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

hono's Issues

Unable to assign a dynamic schema type

Describe the bug

Consider the following factory

import {
	defineI18nMiddleware,
	detectLocaleFromAcceptLanguageHeader
} from '@intlify/hono';

export function createI18nMiddleware<TSchema extends Record<string, string>>(
	schema: TSchema,
	translations: Record<string, TSchema> = {},
) {
	return defineI18nMiddleware<{ message: TSchema }>({
		locale: detectLocaleFromAcceptLanguageHeader,
		messages: { ...translations, en: schema },
		                                               // ^^ <-- TS error
	});
}

The TS error

Type 'TSchema' is not assignable to type 'TSchema extends LocaleMessage<string> ? TSchema : LocaleMessage<string>'.
  Type 'Record<string, string>' is not assignable to type 'TSchema extends LocaleMessage<string> ? TSchema : LocaleMessage<string>'

Not sure if it's me doing something wrong here.

Reproduction

System Info

-

Used Package Manager

other (if you use other package manager, please describe at the Additional context)

Additional context

bun v1.0.12

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.