Created
June 12, 2024 15:41
-
-
Save LorisSigrist/b9c593013e75a22b803c454435eae9b8 to your computer and use it in GitHub Desktop.
Using ParaglideJS with Hono
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 { Hono } from "hono" | |
| import { ParaglideHono } from "./paraglide-hono.js" | |
| import * as runtime from "./paraglide/runtime.js" | |
| import * as m from "./paraglide/messages.js" | |
| // custom function that determines which language should be used based on the Context | |
| function detecLanguage(c) { | |
| const pathname = new URL(c.req.url).pathname; | |
| const parts = pathname.split("/"); | |
| return isAvailableLanguageTag(parts[1]) ? parts[1] : sourceLanguageTag; | |
| } | |
| const app = new Hono(); | |
| app.use(ParaglideHono(runtime, detecLanguage)) // register the middleware | |
| app.get("/*", async (c) => { | |
| const text = m.a_translated_message() // this will return the message in the correct language | |
| return c.text(text); | |
| }); |
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 { AsyncLocalStorage } from "node:async_hooks"; | |
| import { createMiddleware } from "hono/factory"; | |
| /** | |
| * @template {string} T | |
| * @param {any} runtime | |
| * @param {(ctx: import("hono").Context) => import("./paraglide/runtime.js").AvailableLanguageTag} detectLanguage | |
| */ | |
| export function ParaglideHono(runtime, detectLanguage) { | |
| /** @type {AsyncLocalStorage<T>} */ | |
| const localeStorage = new AsyncLocalStorage(); | |
| const middleware = createMiddleware(async (c, next) => { | |
| return localeStorage.run(detectLanguage(c), next); | |
| }); | |
| runtime.setLanguageTag( | |
| () => localeStorage.getStore() || runtime.sourceLanguageTag | |
| ); | |
| return middleware; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment