【问题标题】:setting shared schema for multiple fastify routes为多个 fastify 路由设置共享模式
【发布时间】:2022-10-01 15:09:25
【问题描述】:

我有以下路线

export default async function (fastify) {
  // fastify routes here...
  fastify.get(
    \'/\',
    {
      schema: {
        params: {
          type: \'object\',
          properties: {
            id: {
              type: \'number\',
              description: \'configuration id\',
            },
          },
        },
      },
    },
    async (req) => {
      console.log(req.params);
      return {};
    },
  );
}

// Prefix for fastify autoload
export const autoPrefix = `/configuration/:id/jobs`;

如何在该函数中为我的所有路由设置参数模式,这样我就不会复制我的参数模式:

{
  params: {
    type: \'object\',
    properties: {
      id: {
        type: \'number\',
        description: \'configuration id\',
      },
    },
  },
}

我知道我可以做到:

const params = {
  type: \'object\',
  properties: {
    id: {
      type: \'number\',
      description: \'configuration id\',
    },
  },
};
fastify.get(
  \'/\',
  {
    schema: {
      params,
    },
  },
  async (req) => {
    console.log(req.params);
    return {};
  },
);

但是询问是否有一种方法我不需要为每条路线都这样做

    标签: fastify


    【解决方案1】:

    您可以使用onRoute hook

    const fastify = require('fastify')({ logger: true })
    
    const params = {
      type: 'object',
      properties: {
        id: {
          type: 'number',
          description: 'configuration id'
        }
      }
    }
    
    fastify.addHook('onRoute', function hook (routeOptions) {
      if (!routeOptions.schema) {
        routeOptions.schema = {}
      }
    
      if (!routeOptions.schema.params && routeOptions.path.includes(':id')) {
        routeOptions.schema.params = params
      }
    })
    
    fastify.get('/:id', async (request, reply) => {
      return { hello: 'world' }
    })
    fastify.register(async function plugin (instance, opts) {
      instance.post('/foo', async (request, reply) => {
        return request.body
      })
    }, { prefix: '/:id' })
    
    fastify.ready()
    

    【讨论】:

      猜你喜欢
      • 2023-02-02
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2020-12-24
      • 2018-02-12
      • 2015-06-06
      • 1970-01-01
      相关资源
      最近更新 更多