swagger 通过测试后生成openapi.yml文件

nc1teljy  于 2023-08-11  发布在  其他
关注(0)|答案(1)|浏览(208)

在完成所有测试后(在tap中),我想运行一个生成openapi. yml的脚本。
在.taprc配置中,我添加了after属性:

after: utils/generateOpenApi.ts

字符串
我的脚本(utils/generateOpenApi.ts)看起来像这样:

const helper = require('fastify-cli/helper.js')
import fs from 'fs'
import path from 'path'

const generateOpenApi = async() => {
   const argv = [path.join(__dirname, '..', 'src', 'app.ts')]
   const app = await helper.build(argv, {})
  
   console.log('app.swagger', app.swagger)
   const yaml = app.swagger({ yaml: true });
   fs.writeFileSync("swagger.yaml", yaml);
}

generateOpenApi()


我的主文件(app.ts):

import { FastifyPluginAsync } from "fastify";
import { buildJsonSchemas, register } from "fastify-zod";
import { join } from "path";
import AutoLoad, { AutoloadPluginOptions } from "@fastify/autoload";
import { type FastifyZod } from "fastify-zod";

import { models } from "./routes/users/users.schemas";

export type AppOptions = {
   // Place your custom options for app below here.
} & Partial<AutoloadPluginOptions>;

// Pass --options via CLI arguments in command to enable these options.
const options: AppOptions = {};

declare module "fastify" {
   interface FastifyInstance {
     readonly zod: FastifyZod<typeof models>;
   }
}

const app: FastifyPluginAsync<AppOptions> = async (
   fastify,
   opts
): Promise<void> => {
   await register(fastify, {
     jsonSchemas: buildJsonSchemas(models, { errorMessages: true }),
     swaggerOptions: {
       swagger: {
         info: {
           title: "Fastify API",
           description:
             "Building a blazing fast REST API with Node.js, MongoDB, Fastify and Swagger",
           version: "0.1.0",
         },
         host: "localhost",
         schemes: ["http"],
         consumes: ["application/json"],
       },
     },
     swaggerUiOptions: {
       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, request, reply) => {
         return swaggerObject;
       },
       transformSpecificationClone: true,
     },
   });

   void fastify.register(AutoLoad, {
     dir: join(__dirname, "plugins"),
     options: opts,
   });

   void fastify.register(AutoLoad, {
     dir: join(__dirname, "routes"),
     options: opts,
     ignorePattern: /.*(schemas)\.ts/
   });
};

export default app;
export { app, option


Codesandbox

cbjzeqam

cbjzeqam1#

您需要用fastify-plugin Package app.ts
应用程序的结构如下所示(在左侧):
x1c 0d1x的数据
helper.build(argv, {})函数返回未附加swagger-ui插件的fastify-cli root示例。
因此,如果您使用fastify-plugin来打破封装,则app.ts位于同一父上下文中,并且您可以从helper.build(argv, {})返回的引用访问swagger-ui插件。
进一步阅读:

相关问题