从swagger-node-express spec.js和model.js创build文档

resources.js

'use strict'; var sw = require('swagger-node-express'); var paramTypes = sw.paramTypes; var swe = sw.errors; var petData = require('./service.js'); // the description will be picked up in the resource listing exports.findById = { 'spec': { description : 'Operations about pets', path : '/pet/{petId}', method: 'GET', summary : 'Find pet by ID', notes : 'Returns a pet based on ID', type : 'Pet', nickname : 'getPetById', produces : ['application/json'], parameters : [paramTypes.path('petId', 'ID of pet that needs to be fetched', 'string')], responseMessages : [swe.invalid('id'), swe.notFound('pet')] }, 'action': function (req,res) { console.log('findById call'); if (!req.params.petId) { throw swe.invalid('id'); } var id = parseInt(req.params.petId); var pet = petData.getPetById(id); if(pet) { res.send(JSON.stringify(pet)); } else { throw swe.notFound('pet', res); } } }; 

model.js

 exports.models = { 'Pet':{ 'id':'Pet', 'required': ['id', 'name'], 'properties':{ 'id':{ 'type':'integer', 'format':'int64', 'description': 'Unique identifier for the Pet', 'minimum': '0.0', 'maximum': '100.0' }, 'name':{ 'type':'string', 'description': 'Friendly name of the pet' } } } }; 

您好我正在使用swagger-node-express在我的node.js应用程序。 我成功configuration,它工作正常。

但是现在我正在用swagger-ui来logging问题。 swagger-ui需要JSON文件。 如何从这两个文件生成文件。

Swagger-node-express根据您提供的规范生成json。 你只需要通过调用来告诉它在哪里发布它

 swagger.configureSwaggerPaths('', 'api-docs', ''); 

在[yourdomain] / api-docs中发布json api描述,例如

 localhost:8080/api-docs 

当然,你可以把'api-docs'改成任何你想要的名字。

要使用swagger-ui来检查你的api,你需要把它解压到目录中的某个地方。 矿在../swagger-ui/dist。 告诉express以静态的方式在那里提供文件,并给它一个path,如/ docs:

 var dirname = __dirname + '/../swagger-ui/dist/'; var docs_handler = express.static(dirname); app.get(/^\/docs(\/.*)?$/, function(req, res, next) { if (req.url === '/docs') { // express static barfs on root url w/o trailing slash res.writeHead(302, { 'Location' : req.url + '/' }); res.end(); return; } // take off leading /docs so that connect locates file correctly req.url = req.url.substr('/docs'.length); return docs_handler(req, res, next); }); 

现在指着你的浏览器

 localhost:8080/docs 

应该显示swagger-ui界面。 要使用户界面直接显示您的api规格,请在swagger-ui index.html文件中添加您的api-docs url:

 window.swaggerUi = new SwaggerUi({ url: "/api-docs", 

应该有一个更好的方法来做最后的调整,但我还没有发现。