Fastify Schema如何设置对象内的amount、redirectUrl为必填项?
Fastify嵌套对象Schema必填字段设置方法
问题描述
在Fastify中创建Schema时,如何将对象中的键设置为必填项?我需要将transaction对象下的amount和redirectUrl设为必填字段,但尝试使用transaction.amount的方式并未生效。以下是我编写的createTransactionSchema代码:
const createTransactionSchema = { body: { type: 'object', additionalProperties: false, required: ['merchantUuid', 'transaction'], properties: { merchantUuid: { type: 'string' }, transaction: { type: 'object', required: ['amount', 'redirectUrl', 'address1'], properties: { amount: { type: 'number', format: 'float', minimum: 0.01, maximum: 99999.99 }, redirectUrl: { type: 'string' }, address1: { type: 'string' }, city: { type: 'string', nullable: true }, email: { type: 'string', format: 'email', nullable: true }, firstName: { type: 'string', nullable: true }, invoiceId: { type: 'string', nullable: true }, message: { type: 'string', nullable: true }, mobile: { type: 'integer', nullable: true }, postcode: { type: 'string', nullable: true }, reference: { type: 'string', nullable: true }, service: { type: 'string', nullable: true }, surname: { type: 'string', nullable: true }, tableNumber: { type: 'integer', nullable: true }, } } } }, response: { 200: { type: 'object', properties: { uuid: { type: 'string' } } } } }
正确解决方案
你当前的代码其实已经正确配置了嵌套对象的必填字段——在transaction子对象的配置里,通过required: ['amount', 'redirectUrl', 'address1']指定了该层级下的必填键,这才是Fastify(遵循JSON Schema规范)设置嵌套字段必填的正确姿势。
之前用transaction.amount的写法无效,是因为外层的required数组只能管当前层级的顶级字段(比如这里的merchantUuid、transaction),没法直接写嵌套字段的路径。
核心要点
- 每个对象类型的Schema字段,都得在自己的配置块里单独定义
required数组,用来指定当前层级的必填键。 - 你的代码里,
transaction对象的required数组已经包含了amount、redirectUrl和address1,这三个字段会被Fastify强制校验为必填项,只要请求体里的transaction缺了其中任何一个,都会触发校验失败。
校验示例
如果请求体是下面这种格式,会因为缺少transaction.amount被拒绝:
{ "merchantUuid": "merchant_123", "transaction": { "redirectUrl": "https://your-domain.com/redirect", "address1": "Main Street 100" } }
而包含所有必填字段的请求体就能顺利通过校验:
{ "merchantUuid": "merchant_123", "transaction": { "amount": 50.50, "redirectUrl": "https://your-domain.com/redirect", "address1": "Main Street 100" } }
内容的提问来源于stack exchange,提问作者Dally
相关产品推荐
相关产品推荐

