Skip to content
Open
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
64 changes: 64 additions & 0 deletions docs/usage-i18n.md
Original file line number Diff line number Diff line change
@@ -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: '<locale>' | (() => '<locale>' | 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.
1 change: 1 addition & 0 deletions docs/usage-options-summary.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,6 @@ OpenApiValidator.middleware({
$refParser: {
mode: 'bundle'
},
ajvLocale: 'de' | (() => 'de' | undefined),
});
```
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down