- Published on
Swagger en typescript
5 mins
- Authors
- Name
- Léo Delpon
Ce code implémente un middleware Swagger pour la documentation de l'API dans une application Express. Il définit une classe Swagger qui utilise les modules swagger-autogen et swagger-ui-express pour générer et afficher une documentation d'API Swagger dans un navigateur. La particularité est que ce middleware peut être instancié en Singleton !
Code Blocks
Voici le code :
/**
* Implement swagger middleware for API documentation
*
* @author Léo DELPON <leo.delpon@viacesi.fr>
*/
import { Application } from 'express';
import swaggerAutogen from 'swagger-autogen';
import swaggerUi from 'swagger-ui-express';
import * as path from 'path';
class Swagger {
private static instance: Swagger;
public swaggerUi = swaggerUi;
public swaggerFile = require('../../swagger_output_file.json');
public swaggerAutogen = swaggerAutogen;
private doc = {
info: {
version: '1.0.0',
title: 'My API',
description:
'Documentation automatically generated by the <b>swagger-autogen</b> module.'
},
host: 'localhost:3000',
basePath: '/',
schemes: ['http', 'https'],
consumes: ['application/json'],
produces: ['application/json'],
tags: [
{
name: 'User',
description: 'Endpoints'
}
],
securityDefinitions: {
apiKeyAuth: {
type: 'apiKey',
in: 'header', // can be "header", "query" or "cookie"
name: 'X-API-KEY', // name of the header, query parameter or cookie
description: 'any description...'
}
},
definitions: {
Parents: {
father: 'Simon Doe',
mother: 'Marie Doe'
},
User: {
name: 'Jhon Doe',
age: 29,
parents: {
$ref: '#/definitions/Parents'
},
diplomas: [
{
school: 'XYZ University',
year: 2020,
completed: true,
internship: {
hours: 290,
location: 'XYZ Company'
}
}
]
},
AddUser: {
$name: 'Jhon Doe',
$age: 29,
about: ''
}
}
};
/**
* Will auto generate swagger json
* @constructor
*/
private constructor() {
const filePath = path.join(__dirname, '../../swagger_output_file.json');
const endpointsFiles = ['./src/routes/Api.ts'];
this.swaggerAutogen()(filePath, endpointsFiles, this.doc).then(async () => {
await import('../index');
});
}
public static getInstance(): Swagger {
if (!Swagger.instance) {
Swagger.instance = new Swagger();
}
return Swagger.instance;
}
/**
* It mounts swagger middleware in _express and will be
* displayed in /doc api endpoint
* @param {Application} _express represent the express object
* @returns {Application}
*/
public mount(_express: Application): Application {
_express.use(
'/doc',
this.swaggerUi.serve,
this.swaggerUi.setup(this.swaggerFile)
);
return _express;
}
}
export default Swagger;
Enfin, le code exporte une instance de la classe Swagger pour une utilisation dans d'autres fichiers de code.