简体   繁体   English

当 fastify 请求正文中缺少不同的值时,AJV 验证不会返回多个错误

[英]AJV validation doesn't return multiple errors when different values are missing in the fastify request body

I have a fastify server with a post endpoint.我有一个带有 post 端点的 fastify 服务器。 It accepts a JSON request body with a validation.它接受带有验证的 JSON 请求正文。 Server code below:服务器代码如下:

const fastify = require("fastify");

const server = fastify({
  ajv: {
    customOptions: {
      allErrors: true,
    },
  },
  logger: true,
});
const schema = {
  schema: {
    body: {
      type: "object",
      properties: {
        data: {
          type: "array",
          items: {
            type: "object",
            properties: {
              foo: {
                type: "string",
              },
              bar: {
                type: "string",
              },
            },
            required: ["foo", "bar"],
          },
        },
      },
      required: ["data"],
    },
  },
};
server.post("/", schema, function (request, reply) {
  console.log({
    request: {
      body: JSON.stringify(request.body),
    },
  });
  reply.send({ message: "hello" });
});

server.listen(3000, function (err, address) {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
  console.log(`server listening on ${address}`);
});

Below is a valid request body.下面是一个有效的请求正文。

{ "data":[{ "bar": "bar exists", "foo": "foo exists" }]}

When I try to access the same server with multiple values in input missing ie,当我尝试访问缺少输入的多个值的同一服务器时,即,

{ "data":[{ "bar": "bar exists, foo missing" }, {}] }

I am getting the below response.我收到以下回复。

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "body.data[0] should have required property 'foo', body.data[1] should have required property 'foo', body.data[1] should have required property 'bar'"
}

I want to get each error separately, instead of getting a single large error message as this request can go very large.我想分别获取每个错误,而不是获取单个大错误消息,因为此请求可以 go 非常大。 I have tried a bit of trial around the ajv options but couldn't find anything.我尝试了一些关于 ajv 选项的试验,但找不到任何东西。 Any help is appreciated.任何帮助表示赞赏。 Cheers:)干杯:)

You need to have a custom parser after the error is caught.捕获到错误后,您需要有一个自定义解析器。

In order to achieve this approach, there is a method called setErrorHandler .为了实现这种方法,有一个名为setErrorHandler的方法。

According to Fastify documentation :根据 Fastify 文档

Set a function that will be called whenever an error happens.设置一个 function 将在发生错误时调用。

This is a simple parser, but you may need to change it to your taste:这是一个简单的解析器,但您可能需要根据自己的喜好对其进行更改:

server.setErrorHandler(function (error, request, reply) {
  if (error.validation) {
     reply.status(400).send({ 
      statusCode: error.statusCode,
      error: 'Bad Request',
      message: error.validation.map(err => `${err.instancePath} ${err.message}`)
    });
  }
})

// rest of code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM