如何在 fastify 中使用 ajv-i18n ?

how can i use ajv-i18n in fastify ?

背景

问题

当我将 setErrorHandler 添加到我的 project/index.js 时,它不起作用。

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()

问题

我想用ajv i18n把错误转成中文,怎么办?我这样做,但它不起作用 如何在 fastify 中使用 ajv-i18n ? 我应该在哪里添加 setErrorHandler?

这是一个可以玩的工作片段;我认为您的问题出在路线的架构上。

const Fastify = require('fastify')
const localize = require('ajv-i18n')

const app = Fastify({
  logger: true,
  ajv: {
    customOptions: { allErrors: true, jsonPointers: true }
  }
})

app.post('/', {
  schema: {
    body: {
      type: 'object',
      properties: {
        foo: { type: 'integer' }
      }
    }
  }
}, () => {})

app.setErrorHandler((error, request, reply) => {
  if (error.validation) {
    localize.ru(error.validation)
    reply.status(400).send(error.validation)
    return
  }
  request.log.error({ err: error })
  reply.send(error)
})

app.inject({
  method: 'POST',
  url: '/',
  payload: {
    foo: 'string'
  }
}, (_, res) => {
  console.log(res.json())
})

将打印出:

[
  {
    keyword: 'type',
    dataPath: '/foo',
    schemaPath: '#/properties/foo/type',
    params: { type: 'integer' },
    message: 'должно быть integer'
  }
]

还有另一种方法可以解决这个问题。

感谢:

这是另一种方式:

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) 

和响应示例:

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