Fastify 中正文的条件(if-else)模式验证?

问题描述 投票:0回答:1

是否可以对Fastify中的

request.body
进行条件验证? Fastify 使用
ajv
进行模式验证,但我似乎无法让它工作。

我要么从严格模式收到错误,说我缺少

type
键,要么我让它工作,但我在请求中收到错误,说我的值是必需的,即使它在那里。

所以我的确切问题是,如果

state
值是“US”,我正在尝试验证是否存在
country
值。

我很确定我的语法是正确的,但我觉得我可能把它放在错误的地方......或者它只是不起作用。我的代码如下所示:

fastify.post("/user", {
  schema: {
    description: "Create a user",
    body: {
      type: "object",
      required: ["country"],
      properties: {
        state: { type: "string" },
        country: {
          type: "string",
          enum: ["US", "GB"],
        },
      },
      if: { properties: { country: { const: "US" } } },
      then: { required: ["state"] },
    },
    response: {
      //...
    },
  },
}, function (request, reply) {
  // do something
});

如前所述,我尝试将

if
块移至
properties
甚至内部
country
但似乎没有任何效果。

我在这里做错了什么吗?还是说这不可能?

提前感谢您的帮助

jsonschema fastify ajv
1个回答
1
投票

这是一个工作示例:

const app = require('fastify')({ logger: !true });

const body = {
  type: 'object',
  properties: {
    state: {
      type: 'string',
    },
    country: {
      type: 'string',
      enum: ['US', 'GB'],
    },
  },
  required: ['country'],
  if: {
    properties: {
      country: { const: 'US' },
    },
  },
  then: {
    required: ['state'],
  },
};

app.post(
  '/',
  {
    schema: {
      body,
    },
  },
  async (request, reply) => {
    return request.body;
  }
);

(async function () {
  {
    const res = await app.inject({
      method: 'POST',
      url: '/',
      payload: {
        country: 'US',
      },
    });
    console.log(res.json());
  }

  {
    const res = await app.inject({
      method: 'POST',
      url: '/',
      payload: {
        country: 'GB',
      },
    });
    console.log(res.json());
  }
})();

它将打印:

{
  statusCode: 400,
  error: 'Bad Request',
  message: "body must have required property 'state'"
}
{ country: 'GB' }
© www.soinside.com 2019 - 2024. All rights reserved.