手动搭建koa+ts项目框架(swagger文档篇)

2023-12-19 21:10:33


一、安装依赖

  • swagger-jsdoc
    读取您的JSDoc带注释的源代码并生成OpenAPI (Swagger) 规范
  • koa2-swagger-ui
    根据配置生成swagger界面
npm i swagger-jsdoc koa2-swagger-ui -S
and
npm i @types/swagger-jsdoc -D

二、直接使用json文件生成

无需使用swagger-jsdoc,直接根据json配置数据生成

import Koa from 'koa';
import { koaSwagger } from 'koa2-swagger-ui';

const app = new Koa();

app.use(
  koaSwagger({
    routePrefix: '/swagger', // host at /swagger instead of default /docs
    swaggerOptions: {
      url: 'http://petstore.swagger.io/v2/swagger.json', // example path to json
    },
  }),
);

app.listen(3001);

在这里插入图片描述

三、根据对应api注释生成

使用swagger-jsdoc读取每个接口前面的注释,生成对应json数据后生成

新建swagger.ts文件

项目配置文件新增 /config/swagger.ts

import swaggerJSDoc from 'swagger-jsdoc';
import fs from 'fs'
const options = {
    definition: {
        openapi: '3.0.1',
        info: {
            title: '我是标题',
            version: '1.0.0',
            description: '我是描述',
        },
        //servers的每一项,可以理解为一个服务,实际项目中,可自由修改
        servers: [
            {
                url: '/api',
                description: 'API server',
            },
        ],
    },
    apis: ['./routes/*.ts'],
};

export const swaggerSpec = swaggerJSDoc(options);

// 如果有Swagger规范文件转TS的需求,可在此处保留Swagger规范文件到本地,方便使用
fs.writeFileSync('./dist/swagger.json', JSON.stringify(swaggerSpec, null, 2));

注意 apis 相对于项目更目录而言

新建./routes/users.ts文件

/src/routers新建user.ts文件

const router = require('koa-router')()
import Koa from 'koa'

// import Router from 'koa-router'
// const router = new Router();

/**
* @swagger
* tags:
*   name: Users
*   description: User management
*/

/**
* @swagger
* components:
*   schemas:
*     User:
*       type: object
*       properties:
*         id:
*           type: integer
*           description: The user ID.
*         name:
*           type: string
*           description: The user's name.
*         email:
*           type: string
*           description: The user's email.
*       required:
*         - id
*         - name
*         - email
*/

/**
* @swagger
* /users:
*   get:
*     summary: Retrieve a list of users
*     tags: [Users]
*     responses:
*       200:
*         description: A list of users.
*         content:
*           application/json:
*             schema:
*               type: array
*               items:
*                 $ref: '#/components/schemas/User'
*/
router.get('/users', async (ctx: Koa.Context) => {
    const users = [
        { id: 1, name: 'userName', email: 'email.com' },
    ];
    ctx.body = users;
});
export default router

入口文件引入对应数据

可使用以下两个方式

import Koa from 'koa';
const Router = require('koa-router');
import { koaSwagger } from 'koa2-swagger-ui';
import swaggerSpec from '../config/swagger';
import usersRoutes from '../routes/users';

const app = new Koa();
const router = new Router();

router.use('/api', usersRoutes.routes(), usersRoutes.allowedMethods());

app.use(
  koaSwagger({
    routePrefix: '/swagger', // host at /swagger instead of default /docs
    swaggerOptions: {
      spec: swaggerSpec as Record<string, unknown>,
    },
  }),
);

app.use(router.routes()).use(router.allowedMethods());

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});

或者

import Koa from 'koa';
const Router = require('koa-router');
const swaggerUI = require('koa2-swagger-ui').koaSwagger;
import swaggerSpec from '../config/swagger';
import usersRoutes from '../routes/users';

const app = new Koa();
const router = new Router();

router.use('/api', usersRoutes.routes(), usersRoutes.allowedMethods());


router.get(
    '/swagger',
    swaggerUI({
        routePrefix: false,
        swaggerOptions: {
            spec: swaggerSpec,
        },
    })
);

app.use(router.routes()).use(router.allowedMethods());

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});

编译构建或者实时编译
访问http://localhost:3000/swagger

在这里插入图片描述

如果swagger.ts文件的 apis配置有误会出现下图提示

在这里插入图片描述


如有启发,可点赞收藏哟~

文章来源:https://blog.csdn.net/weiCong_Ling/article/details/135079887
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。