如何使用Fastify使一条路由具有多个架构的不同参数?

问题描述

我在中间件中使用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只是所有汽车属性的列表。我想要的是以下内容

  1. 我可以使用一种模式根据路由中的不同选项返回自定义属性吗?
  2. 如果无法实现1,我可以为每种选项组合提供4种不同的方案吗?

我不确定该如何处理。谢谢!

解决方法

我可以使用一种模式根据路由中的不同选项返回自定义属性吗?

是的,可以。

在此示例中,返回的数据相同,但是一个端点返回:

# /
{ 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' }
    ]
  })
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...