Swagger
ตัวช่วยในการสร้าง api document โดยจะมี live render จาก api-description ที่เราเขียนมาแสดง แล้วก็สามารถยิง request ได้จริงๆ
install
npm install swagger-jsdoc swagger-ui-express swagger-autogen
npm install @types/swagger-jsdoc @types/swagger-ui-express
#create File “src/swagger/swagger.ts”
const swaggerAutogen = require('swagger-autogen')();
const doc = {
info: {
version: '', // by default: '1.0.0'
title: '', // by default: 'REST API'
description: '', // by default: ''
},
host: '', // by default: 'localhost:3000'
basePath: '', // by default: '/'
schemes: [], // by default: ['http']
consumes: [], // by default: ['application/json']
produces: [], // by default: ['application/json']
tags: [ // by default: empty Array
{
name: '', // Tag name
description: '', // Tag description
},
// { ... }
],
securityDefinitions: {
apiKeyAuth:{
type: "apiKey",
in: "header", // can be "header", "query" or "cookie"
name: "x-access-token",
description: ""
}}, // by default: empty object (Swagger 2.0)
definitions: {
Login: {
userId: "540002",
password: "0",
org: "OPP",
trackingstatus: "T"
},
},// by default: empty object
components: {} // by default: empty object (OpenAPI 3.x)
};
const outputFile = './src/swagger/swagger-output.json';
const endpointsFiles = ['./src/routes/index.ts'];
/* NOTE: if you use the express Router, you must pass in the
'endpointsFiles' only the root file where the route starts,
such as: index.js, app.js, routes.js, ... */
swaggerAutogen(outputFile, endpointsFiles, doc);
สร้าง route สำหรับดู document
#File “Index.ts”
import swaggerUi from 'swagger-ui-express';
import swaggerFile from './swagger/swagger-output.json';
app.use('/doc', swaggerUi.serve, swaggerUi.setup(swaggerFile))
เพิ่ม script สำหรับ gen api document
#package.json
"swagger-gen": "ts-node src/swagger/swagger.ts"
Last updated