如何使用TypeScript设置@fastify/swagger和@fastify/swagger-ui?

dldeef67  于 2023-05-06  发布在  TypeScript
关注(0)|答案(1)|浏览(193)

我是新来的Fastify,我正试图用它来设置 Swagger 的文档。我使用TypeScript,我发现的所有示例都使用JavaScript和require语法。
我尝试在可能的情况下遵循示例,现在我的文档没有显示我创建的/路由的任何内容。
以下是我的当前代码:

import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUi from '@fastify/swagger-ui';
import Fastify from 'fastify';

import { errorBoundary } from './plugins/errorBoundary';

const fastify = Fastify({
  logger: true
});

const port = process.env.PORT || 3003;

// Set custom error handler.
fastify.setErrorHandler(errorBoundary);

// Register @fastify/swagger plugin.
fastify.register(fastifySwagger, {
  openapi: {
    info: {
      title: 'Forest Fire API',
      description: 'Forest Fire API Documentation',
      version: '1.0.0'
    },
    servers: [
      {
        url: 'http://localhost'
      }
    ],
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http',
          scheme: 'bearer'
        }
      }
    },
    tags: [
      {
        name: 'Root',
        description: 'Root endpoints'
      }
    ]
  }
});

// Register @fastify/swagger-ui plugin.
fastify.register(fastifySwaggerUi, {
  routePrefix: '/docs',
  uiConfig: {
    docExpansion: 'full',
    deepLinking: false
  },
  uiHooks: {
    onRequest: function (_request, _reply, next) {
      next();
    },
    preHandler: function (_request, _reply, next) {
      next();
    }
  },
  staticCSP: true,
  transformStaticCSP: (header) => header,
  transformSpecification: (swaggerObject) => {
    return swaggerObject;
  },
  transformSpecificationClone: true
});

// Root route.
fastify.get(
  '/',
  {
    schema: {
      description: 'Root endpoint',
      tags: ['Root'],
      response: {
        200: {
          description: 'Succesful response',
          type: 'object',
          properties: {
            message: { type: 'string' },
            result: { type: 'object', nullable: true }
          }
        }
      }
    }
  },
  async function (request, reply) {
    return reply.send({
      message: 'Hello World',
      result: null
    });
  }
);

async function start() {
  await fastify.listen({
    port: port as number
  });

  fastify.swagger();
}

start().catch((err) => {
  fastify.log.error(err);
  process.exit(1);
});

当我访问/docs路由时,显示以下内容:

我希望/路由会在页面中记录下来。可能的错误有哪些?

goucqfw6

goucqfw61#

说明

你需要注册route作为插件,以使路由出现在swagger中。

app.register((app, options, done) => {
        app.get("/", {
            schema: {
                tags: ["Default"],
                response: {
                    200: {
                        type: "object",
                        properties: {
                            anything: { type: "string" },
                        },
                    },
                },
            },
            handler: (req, res) => {
                res.send({ anything: "meaningfull" });
            },
        });
        done();
    });

完整代码:

import dotenv from "dotenv";
import { fastify } from "fastify";
import fastifySwagger from "@fastify/swagger";
import fastifySwaggerUi from "@fastify/swagger-ui";
dotenv.config();
const app = fastify({ logger: true });

const swaggerOptions = {
    swagger: {
        info: {
            title: "My Title",
            description: "My Description.",
            version: "1.0.0",
        },
        host: "localhost",
        schemes: ["http", "https"],
        consumes: ["application/json"],
        produces: ["application/json"],
        tags: [{ name: "Default", description: "Default" }],
    },
};

const swaggerUiOptions = {
    routePrefix: "/docs",
    exposeRoute: true,
};

app.register(fastifySwagger, swaggerOptions);
app.register(fastifySwaggerUi, swaggerUiOptions);

app.register((app, options, done) => {
    app.get("/", {
        schema: {
            tags: ["Default"],
            response: {
                200: {
                    type: "object",
                    properties: {
                        anything: { type: "string" },
                    },
                },
            },
        },
        handler: (req, res) => {
            res.send({ anything: "meaningfull" });
        },
    });
    done();
});

app.listen(
    {
        port: Number(process.env.APP_PORT) ?? 3000, // Pulled from env file.
        host: process.env.APP_HOST ?? "localhost",
    },
    (err, address) => {
        if (err) {
            console.error(err);
            process.exit(1);
        }
    }
);

相关问题