Reputation: 2216
I have a fastify API service with the below endpoint.
server.route({
method: 'PUT',
url: '/user/order/new',
schema: {
description: 'place a new order',
body: {
type: 'object',
required: ['gross', 'name', 'surname', 'address', 'city', 'country', 'phone', 'email', 'cart'],
properties: {
gross: {
type: 'number',
description: 'order total'
},
name: {
type: 'string',
description: 'first name'
},
surname: {
type: 'string',
description: 'last name'
},
address: {
type: 'string',
description: 'street address'
},
city: {
type: 'string',
description: 'mailing city'
},
province: {
type: 'string',
description: 'state'
},
country: {
type: 'string',
description: 'country of residence'
},
phone: {
type: 'string',
description: 'telephone number'
},
email: {
type: 'string',
description: 'email address'
},
subscribe: {
type: 'boolean',
description: 'subscribe to newsletter'
},
privacy: {
type: 'boolean',
description: 'accepted privacy policy'
},
waiver: {
type: 'boolean',
description: 'accepted waiver'
},
card: {
type: 'boolean',
description: 'first name'
},
expires: {
type: 'boolean',
description: 'expiration date entered'
},
cvv: {
type: 'boolean',
description: 'CVV entered'
},
postal: {
type: 'string',
description: 'card billing zip'
},
cart: {
type: 'array',
description: 'shopping cart',
items: {
type: 'object',
properties: {
id: {
type: 'integer',
description: 'item id'
},
title: {
type: 'string',
description: 'entry title'
},
price: {
type: 'number',
description: 'price of a single item'
},
quantity: {
type: 'integer',
description: 'number of items of this kind'
}
}
}
},
coupon: {
type: 'string',
description: 'discount code'
},
payment: {
type: 'object',
description: 'stripe payment object'
}
}
},
response: {
200: {
description: 'Successful response',
type: 'object',
properties: {
id: {
type: 'integer',
description: 'the new order id'
}
}
},
500: {
description: 'Internal Server Error',
type: 'object',
properties: {
statusCode: { type: 'integer' },
code: { type: 'integer' },
error: { type: 'string' },
message: { type: 'string' }
}
}
}
},
handler: async (req, res) => {
...
My handler code is working fine. The logic inside the handler dictates that if the card flag is set to false, the payment is processed for cash, and the payment
object will be null. Otherwise, payment has a bunch of things returned to me by Stripe.
However, if I document with the above schema
using fastify-swagger
, validation is failing for cash payments - eg when payment is set to null
.
The error is below:
"validation":[{"keyword":"type","dataPath":".payment","schemaPath":"#/properties/payment/type","params":{"type":"object"},"message":"should be object"}],"validationContext":"body"},"msg":"body.payment should be object","v":1}
What should I do to make the payment
accept either 'object' or null?
Upvotes: 1
Views: 2459
Reputation: 2216
I found a working solution:
payment: {
type: ['object', 'null'],
description: 'stripe payment object'
}
Upvotes: 1