node.js - 将 swagger 添加到我的 Nodejs Restify 项目

标签 node.js swagger restify

我有一个基本的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)
})

最佳答案

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

所以我使用的包名为restify-swagger-jsdoc 而且配置非常简单,您将需要

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

npm 我restify-swagger-jsdoc

然后在初始化 const server = Restify.createServer() 的文件中添加以下代码片段

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 文档。

关于node.js - 将 swagger 添加到我的 Nodejs Restify 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66167025/

相关文章:

node.js - NodeJs 中的完整聊天解决方案

javascript - 鼠标单击特定窗口/背景窗口(nodejs)

c# - 如何配置 Swagger/Swashbuckle 自定义序列化程序 IControllerConfiguration ASP.NET WebAPI

angularjs - Passport 在调用 passport.authenticate ('facebook' 后,如何在不重定向用户的情况下获取 facebook 重定向 uri

node.js - 大多数特定 URI 的类似键值的存储

node.js - 可以让事件处理程序等到异步/基于 Promise 的代码完成吗?

node.js - 如何迭代全局和本地 npm 包的 package.json 文件?

c# - Swagger 的服务堆栈不起作用

请求正文对象的各个成员的 C# swagger 文档

node.js - 为 restify.js 实现基于 token 的身份验证的最佳方法是什么?