express-openapi-validator
express-openapi-validator copied to clipboard
Internationalization / i18n
Is your feature request related to a problem? Please describe. Validation error messages are english
Describe the solution you'd like The possibility to localize error messages
Additional context Ajv seems to support this, but how can we achieve i18n with this middleware?
Monkey patching hack, only works for body parameters though :(
import {ErrorObject} from "ajv";
import {ValidationError} from "express-openapi-validator/dist/framework/types";
import {ajvErrorsToValidatorError} from "express-openapi-validator/dist/middlewares/util";
import localize from "ajv-i18n/localize/de";
/**
* express-openapi-validator uses ajv to do the validation
* ajv supports i18n via ajv-i18n
* but express-openapi-validator doesn't seem to expose the integration with ajv enough to achieve i18n
* we patch express-openapi-validator's 'ajvErrorsToValidatorError' function to translate the messages
* before the ajv types are mapped to express-openapi-validator's types because after that too much context is lost
* to do the translation
*/
type AjvToValidationErrorFunction = (
status: number,
errors: ErrorObject[],
) => ValidationError
const originalFunction : AjvToValidationErrorFunction = ajvErrorsToValidatorError as unknown as AjvToValidationErrorFunction
const patchedFunction : AjvToValidationErrorFunction = (status, errors) => {
// translate errors to german
localize(errors)
return originalFunction(status, errors)
}
// overwrite the function exported by express-openapi-validator to use our patched variant
// @ts-ignore
ajvErrorsToValidatorError = patchedFunction