【问题标题】:Adding swagger to my nodejs restify project向我的 nodejs restify 项目添加招摇
【发布时间】:2021-05-15 22:03:55
【问题描述】:

我有一个基本的 nodejs restify 服务器,它有两种简单的方法,一种是 GET,一种是 POST。我正在尝试在我的 restify 服务之上添加 swagger API 文档。找到了对 express 的支持。

还发现了一些库 https://www.npmjs.com/package/swagger-restify 。 但不知道如何在代码中使用它。如何以某种方式添加它,我的所有 api 文档都将出现在 'http://localhost:5000/docs' 或类似的东西中。

我的基本 restify 代码如下。

var restify=require('restify');
var restifyPlugins = require('restify-plugins');
var cors = require('cors');
var server=restify.createServer({name:'test'});

server.use(restifyPlugins.acceptParser(server.acceptable));
server.use(restifyPlugins.queryParser());
server.use(restifyPlugins.fullResponse());
server.use(restifyPlugins.bodyParser({
    maxBodySize: 0,

    multiples: true
}));

server.use(cors({
    origin: '*',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    credentials:'false',
    optionsSuccessStatus: 200 /* some legacy browsers (IE11, various SmartTVs) choke on 204 */ ,
}))

server.use(restifyPlugins.authorizationParser());


server.get({path:'/test'},function(req,res,next){
    
    console.log("TEST API")
    res.send("hello");
    });

server.post({path:'/postCheck'},function(req,res,next){

    console.log("TEST post API",req.body.userId)
    res.send("hello post");
    });



server.listen(5000,function(){
    console.log("Starting server at :%s,%s",server.url,server.name)
})

【问题讨论】:

    标签: node.js swagger restify


    【解决方案1】:

    在你启动你的服务器之前,只需将一个swagger资源设置为swagger-restify文档:

    // import swagger lib
    var swagger = require('swagger-restify');
    
    ...
    swagger.init(server, { // set up swagger for "server"
        apiVersion: '1.0',
        swaggerVersion: '1.0',
        swaggerURL: '/docs', // endpoint what you want to access
        swaggerJSON: '/api-docs.json',
        swaggerUI: './public',
        basePath: 'http://localhost:5000',
        info: {
          title: 'swagger-restify sample app',
          description: 'Swagger + Restify = {swagger-restify}'
        },
        apis: ['./api.js', './api.yml'],
        middleware: function(req, res){}
    });
    
    server.listen(5000,function(){
        console.log("Starting server at :%s,%s",server.url,server.name)
    })
    

    【讨论】:

      【解决方案2】:

      根据swagger-restify 文档,在初始化swagger 时,需要将apis 属性作为数组传递,其中包含API 定义文件名及其相对路径。 API 定义可以通过使用 jsdoc cmets 或创建 yml 文件来完成 参考swagger-restify 文档可以清楚地了解 API 定义的创建,因为它包含两种方法的示例。

      此外,您需要将 swagger UI 相关的 HTML 组件添加到提供静态内容的文件夹中,并且需要在 swagger 配置中包含路径作为swaggerUI 属性。

      对于以下代码段,我假设它们位于 ./public 文件夹中。

      这样配置服务器,

      var restify=require('restify');
      var restifyPlugins = require('restify-plugins');
      var swagger = require('swagger-restify');
      var cors = require('cors');
      var server=restify.createServer({name:'test'});
      
      server.use(restifyPlugins.acceptParser(server.acceptable));
      server.use(restifyPlugins.queryParser());
      server.use(restifyPlugins.fullResponse());
      server.use(restifyPlugins.bodyParser({
          maxBodySize: 0,
      
          multiples: true
      }));
      
      
        swagger.init(server, {
          apiVersion: '1.0',
          swaggerVersion: '1.0',
          swaggerURL: '/docs',
          swaggerUI: './public',
          basePath: 'http://localhost:5000',
          info: {
            title: 'swagger-restify sample app',
            description: 'Swagger + Restify = {swagger-restify}'
          },
          apis: ['./api.js', './api.yml'],
          middleware: function(req, res){}
        });
      
      
      server.use(cors({
          origin: '*',
          methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
          credentials:'false',
          optionsSuccessStatus: 200 /* some legacy browsers (IE11, various SmartTVs) choke on 204 */ ,
      }))
      
      server.use(restifyPlugins.authorizationParser());
      
      
      server.get({path:'/test'},function(req,res,next){
          
          console.log("TEST API")
          res.send("hello");
          });
      
      server.post({path:'/postCheck'},function(req,res,next){
      
          console.log("TEST post API",req.body.userId)
          res.send("hello post");
          });  
      
      
      
      server.listen(5000,function(){
          console.log("Starting server at :%s,%s",server.url,server.name)
      });
      

      【讨论】:

        【解决方案3】:

        所以我确实设法将 Swagger 文档添加到我的 Node.js 和 Restify api。而且我希望有人觉得这很有帮助,并且没有任何东西被弃用。

        所以我使用的包叫做restify-swagger-jsdoc 而且很容易配置,你需要

        https://www.npmjs.com/package/restify-swagger-jsdoc

        npm i restify-swagger-jsdoc

        然后在你初始化const server = restify.createServer()的文件中添加以下代码sn-p

        const restifySwaggerJsdoc = require('restify-swagger-jsdoc');
        
        restifySwaggerJsdoc.createSwaggerPage({
          title: 'API documentation',
          version: '1.0.0',,
          server: server, // created restify server object,
          path: '/api-docs', // url to view generated docs,
          apis: ['./src/routes/*.js'], // this is where swagger can find 
                                       // files containing jsdoc or can point 
                                       // to api.yaml file
                                       // to generate docs from. 
        });
        
        

        一旦您运行服务器并将 jsdoc swagger 注释和注释添加到您的路由中,您应该能够在上述路径中查看生成的 Swagger 文档。

        【讨论】:

          猜你喜欢
          • 2021-04-16
          • 2021-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-22
          • 1970-01-01
          • 1970-01-01
          • 2021-05-22
          相关资源
          最近更新 更多