diff --git a/docs/usage-i18n.md b/docs/usage-i18n.md new file mode 100644 index 0000000..5bdbe32 --- /dev/null +++ b/docs/usage-i18n.md @@ -0,0 +1,64 @@ +--- +title: ▪️ ajvLocale (i18n) +--- + +Localizes AJV validation error messages using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n). + +!!! Option-schema + ```javascript + ajvLocale: '' | (() => '' | undefined) + ``` + +## ajvLocale (optional) + +- `string` – a static locale key applied to every request (e.g. `'de'`, `'ru'`, `'zh'`). +- `() => string | undefined` – a function called on every validation failure. Return a locale key to translate errors, or `undefined` / an unrecognised key to fall back to English. +- `undefined` (**default**) – no translation; errors are returned in English. + +Supported locale keys: `ar`, `ca`, `cs`, `de`, `en`, `es`, `fi`, `fr`, `hu`, `id`, `it`, `ja`, `ko`, `nb`, `nl`, `pl`, `pt-BR`, `ru`, `sk`, `sv`, `th`, `tr`, `uk`, `vi`, `zh`. + +--- + +### Static locale + +All validation errors are translated into the specified language. + +```javascript +app.use( + OpenApiValidator.middleware({ + apiSpec: './openapi.yaml', + ajvLocale: 'de', // German error messages + }), +); +``` + +--- + +### Dynamic locale (per-request) + +Pass a function to resolve the locale at the time the error occurs. This works with any request-scoped mechanism such as Node's built-in `AsyncLocalStorage`: + +```javascript +import { AsyncLocalStorage } from 'async_hooks'; + +const localeStorage = new AsyncLocalStorage(); + +// Upstream middleware – store the locale for the current request +app.use((req, res, next) => { + const lang = req.headers['accept-language']?.split(',')[0]?.trim() ?? 'en'; + localeStorage.run(lang, next); +}); + +app.use( + OpenApiValidator.middleware({ + apiSpec: './openapi.yaml', + ajvLocale: () => localeStorage.getStore(), // called fresh on every request + }), +); +``` + +--- + +### Behaviour for unknown or missing locales + +If the locale key is not recognised by `ajv-i18n` (e.g. `'xx-UNKNOWN'`), or if the function returns `undefined`, errors are returned in English without throwing. diff --git a/docs/usage-options-summary.md b/docs/usage-options-summary.md index 4a6437b..90d28da 100644 --- a/docs/usage-options-summary.md +++ b/docs/usage-options-summary.md @@ -43,5 +43,6 @@ OpenApiValidator.middleware({ $refParser: { mode: 'bundle' }, + ajvLocale: 'de' | (() => 'de' | undefined), }); ``` \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index 3dcfcbc..4e44941 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -60,6 +60,7 @@ nav: - usage-file-uploader.md - usage-ref-parser.md - usage-coerce-types.md + - usage-i18n.md - Guides: - Standard API Server: guide-standard.md