Skip to content

Instantly share code, notes, and snippets.

@SleepWalker
Last active May 28, 2024 01:35
Show Gist options
  • Save SleepWalker/3ca4d22dc66c68a6d19fef9451563d55 to your computer and use it in GitHub Desktop.
Save SleepWalker/3ca4d22dc66c68a6d19fef9451563d55 to your computer and use it in GitHub Desktop.
swagger-jsdoc with koa2-swagger-ui middleware example

This is an example how to setup swagger docs api endpoint for your koa app.

Usage

const Koa = require('koa');
const path = require('path');
const http = require('http');

const swagger = require('./swagger');

const app = new Koa();
const server = http.createServer(app.callback());

swagger(app, {
  title: 'The Service',
  version: '1.0.0',
  apiUrl: 'https://github.com/api',
  parseOnRequest: process.env.NODE_ENV !== 'production',
  apis: [
    path.join(process.cwd(), '/src/actions/**/*.js'),
    path.join(process.cwd(), '/src/models/**/*.js'),
  ],
  securityDefinitions: {
    jwt: {
      description: 'Api auth token',
      type: 'apiKey',
      name: 'Authorization',
      in: 'header',
    },
  },
});

server.listen(3000, () => {
  console.log(`Server is listening on http://0.0.0.0:3000`);
});
const swaggerJSDoc = require('swagger-jsdoc');
const koaSwagger = require('koa2-swagger-ui');
/**
* @typedef {import('koa')} Koa
*/
/**
* For other options see `koa2-swagger-ui` docs
*
* @typedef {object} MiddlewareConfig
* @property {string} apiUrl
* @property {string} title - service name
* @property {string} version - service version
* @property {boolean} parseOnRequest - Whether we should re-parse jsDocs
* from all the source code on each request. Useful for development mode (a.k.a. watch mode)
* @property {string[]} apis - glob patterns for `swagger-jsdoc` to look for jsdocs
* @param {{[key: string]: any}=} params.securityDefinitions - configure api key requirements
*/
/**
* @param {Koa} app
* @param {MiddlewareConfig} config
* @param {{[key: string]: any}=} params.securityDefinitions
*
* @returns {void}
*/
function createSwaggerMiddleware(
app,
{ apiUrl, version, title, parseOnRequest, apis, securityDefinitions },
) {
const swaggerJsonPath = '/api/swagger.json';
let swaggerSpec;
app.use((ctx, next) => {
if (ctx.path === swaggerJsonPath) {
if (!swaggerSpec || parseOnRequest) {
// swagger 2.0
// swaggerSpec = swaggerJSDoc({
// apis,
// definition: {
// info: {
// title,
// version,
// },
// securityDefinitions,
// basePath: '',
// host: new URL(apiUrl).host,
// },
// });
// openapi 3.0
swaggerSpec = swaggerJSDoc({
apis,
definition: {
openapi: '3.0.0',
info: {
title,
version,
},
securityDefinitions,
servers: [
{
url: apiUrl,
},
],
},
});
}
ctx.body = swaggerSpec;
return;
}
return next();
});
app.use(
// @ts-ignore
koaSwagger({
title,
swaggerVersion: '3.30.2',
routePrefix: '/api/swagger',
swaggerOptions: {
url: apiUrl + swaggerJsonPath,
},
hideTopbar: true,
}),
);
}
module.exports = createSwaggerMiddleware;
@yxdYXD11123123
Copy link

did you find the document about this ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment