【问题标题】:how can i use ajv-i18n in fastify ?我如何在 fastify 中使用 ajv-i18n?
【发布时间】:2020-11-20 01:06:29
【问题描述】:

背景

  • fastify
  • json 架构
  • ajv

问题

当我将 setErrorHandler 添加到我的项目/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?

【问题讨论】:

  • 如果有的话,你能添加你的错误模式吗?它们被app.route(route)隐藏了

标签: ajv fastify


【解决方案1】:

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

谢谢:

这是另一种方式:

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"
}

【讨论】:

    【解决方案2】:

    这里有一个可以工作的 sn-p;我认为您的问题出在路线的架构上。

    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'
      }
    ]
    

    【讨论】:

    • 如果对您有帮助,您介意接受答案吗?
    猜你喜欢
    • 2021-04-19
    • 2018-06-05
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    相关资源
    最近更新 更多