需要的包:
npm i koa2-swagger-ui swagger-jsdoc
app/index.js
import Koa from "koa";
import Router from "@koa/router";
import { koaSwagger } from "koa2-swagger-ui";
import fs from "fs";
import swagger from "./swagger.js";
import info from "./api/info.js";
const { version } = JSON.parse(fs.readFileSync("./package.json"));
const app = new Koa();
const router = new Router();
router.get("/", (ctx, next) => {
ctx.body = `Simple game service v${version}`;
});
router.get("/info", (ctx, next) => {
info(ctx);
});
app.use(router.routes()).use(router.allowedMethods());
app.use(swagger.routes(), swagger.allowedMethods())
app.use(
koaSwagger({
routePrefix: "/swagger",
swaggerOptions: {
url: "/swagger.json",
},
})
);
app.listen(3000);
./swagger.js:
import Router from "@koa/router";
import swaggerJSDoc from "swagger-jsdoc";
import fs from "fs";
const { version } = JSON.parse(fs.readFileSync("./package.json"));
const router = new Router();
const options = {
definition: {
openapi: "3.0.0",
info: {
title: "Simple game service",
version,
},
},
apis: ["./app/api/*.js"],
};
const swaggerSpec = await swaggerJSDoc(options);
router.get("/swagger.json", async function (ctx) {
ctx.set("Content-Type", "application/json");
ctx.body = swaggerSpec;
});
export default router;
api/info.js:
import config from "config";
let { host_url } = config.get("settings");
/**
* @openapi
* /info:
* get:
* description: 获取基本配置信息
* responses:
* 200:
* description: 配置信息对象.
* content:
* application/json:
* schema:
* type: object
* properties:
* host_url:
* type: string
*/
let info = function (ctx) {
ctx.body = {
host_url,
};
};
export default info;