问题描述
我在中间件中使用fastify的路线如下:
Route.ts server.get('/ rest / api / cars /:twofourdoors /:autoManual /',{schema:getCaRSSchema},getCars(server));
基本上,用户在此路线中有4个选项,两个或四个门,自动或手动。我的.schema中只有一个架构,例如: schema.ts
const carSchema = {
type: 'object',properties: {
wheels: { type: 'string' },color: { type: 'string' },gears: { type: 'string' },maxAutoSpeed: { type: 'string' },maxManualSpeed: { type: 'string' },twodoorSize: { type: 'string' },fourDoorSize: { type: 'string' },},};
export const getCaRSSchema = {
summary: 'Get cars',description: 'Get cars by types',query: querySchema,response: {
200: {
type: 'object',properties: {
totalItems: { type: 'number' },pageNumber: { type: 'number' },items: { type: 'array',items: carSchema },501: logMessageSchema,};
carSchema只是所有汽车属性的列表。我想要的是以下内容:
我不确定该如何处理。谢谢!
解决方法
我可以使用一种模式根据路由中的不同选项返回自定义属性吗?
是的,可以。
在此示例中,返回的数据相同,但是一个端点返回:
# /
{ items: [ { wheels: 4,serial: '123ASC',color: 'red' } ] }
# /no-serial
{ items: [ { wheels: 4,color: 'red' } ] }
const fastify = require('fastify')()
fastify.get('/',{
handler,schema: {
response: {
200: {
type: 'object',properties: {
items: {
type: 'array',items: {
type: 'object',properties: {
wheels: { type: 'number' },serial: { type: 'string' },color: { type: 'string' }
}
}
}
}
}
}
}
})
fastify.get('/no-serial',color: { type: 'string' }
}
}
}
}
}
}
}
})
fastify.inject('/',(err,res) => {
console.log(res.json())
})
fastify.inject('/no-serial',res) => {
console.log(res.json())
})
function handler (request,reply) {
reply.send({
items: [
{ wheels: 4,color: 'red' }
]
})
}