註解寫在Code內生成swagger UI
註解寫在Code內生成swagger UI
安裝
yarn add swagger-jsdoc swagger-ui-express swagger-model-validator使用
const express = require('express')
const router = express.Router()
const options = {
swaggerDefinition: {
info: {
title: 'REST - Swagger',
version: '1.0.0',
description: 'REST API with Swagger doc',
contact: {
email: ''
}
},
tags: [
{
name: 'AMSS5',
description: 'AMSS5 API'
}
],
schemes: ['http'],
host: 'localhost:3124',
basePath: '/api'
}, // 下面記得要寫上要讀哪邊的註解
apis: ['./router/grid.js', './router/project.js', './router/user.js', './database/schemas/grid.js']
}
const swaggerJSDoc = require('swagger-jsdoc')
const swaggerUi = require('swagger-ui-express')
const swaggerSpec = swaggerJSDoc(options)
require('swagger-model-validator')(swaggerSpec)
router.get('/json', function (req, res) {
res.setHeader('Content-Type', 'application/json')
res.send(swaggerSpec)
})
router.use('/', swaggerUi.serve, swaggerUi.setup(swaggerSpec))
function validateModel (name, model) {
const responseValidation = swaggerSpec.validateModel(name, model, false, true)
if (!responseValidation.valid) {
console.error(responseValidation.errors)
throw new Error(`Model doesn't match Swagger contract`)
}
}
module.exports = router;加入Redoc
Last updated