Search code examples
ajvfastify

how can i use ajv-i18n in fastify ?


Background

  • fastify
  • json schema
  • ajv

Problem

when i add the setErrorHandler to my project/index.js,it doesnt work.

require('module-alias/register')
const Fastify = require('fastify')
const PORT = process.env.PORT || 3000
const sequelize = require('./orm')
const swagger = require('./config').swagger
const localize = require('ajv-i18n')
const app = Fastify({
  logger: {
    prettyPrint: true
  },
  ajv: {
    customOptions: {allErrors: true, jsonPointers: true },
    plugins: [
      require('ajv-errors')
    ]
  }
})
app.register(require('fastify-sensible'))
app.register(require('fastify-swagger'), swagger)
app.register(require('./plugin/systemlogs'))
app.register(require('./plugin/authenticate')).then(()=>{
    const routes = require('./routes')
    routes(app).forEach((route, index) => {
      app.route(route)
    })
})
app.setErrorHandler((error,request,reply)=>{
  if (error.validation) {
    localize.ru(error.validation)
    reply.status(400).send(error.validation)
    return
  }
  reply.send(error)
})

const start = async () => {
  try {
    await sequelize.sync({})
    app.log.info('database sync correctly')
    await app.listen(PORT, '0.0.0.0')
    app.swagger()
  } catch (err) {
    app.log.error(err)
    process.exit(1)
  }
}
start()

Question

i want to turn the error to chinese with ajv i18n ,what should i do? i do in this way but it doesnt work how can i use ajv-i18n in fastify ? where should i add the setErrorHandler?


Solution

  • there are another way to deal with this issue.

    thanks:

    this is another way:

    const fastify = require('fastify')
    const localize = require('ajv-i18n')
    
    const app = fastify({
      ajv: {
        customOptions: { allErrors: true, jsonPointers: true },
        plugins: [
          require('ajv-errors')
        ]
      },
      schemaErrorFormatter: (errors, dataVar) => {
        localize.ru(errors);
        const myErrorMessage = errors.map(error => error.message.trim()).join(', ');
        return new Error(myErrorMessage)
      }
    })
    
    app.get('/', {
      schema: {
        querystring: {
          type: "object",
          properties: { a: { type: "string", nullable: false } },
          required: ["a"],
        },
      },
    }, async function (req, res) {})
    
    app.listen(3000) 
    

    and example of response:

    {
      "statusCode": 400,
      "error": "Bad Request",
      "message": "должно иметь обязательное поле a"
    }