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'
}
}
}
};
您好,我在node.js应用程序中使用了swagger-node-express。我成功地进行了配置,它工作得很好。
但是现在我在使用swagger-ui进行文档记录时遇到了问题。swagger-ui需要JSON文件。如何从这两个文件生成文档。
发布于 2015-05-09 14:10:56
Swagger-node-express根据您提供的规范生成json。你只需要通过调用告诉它发布到哪里
swagger.configureSwaggerPaths('', 'api-docs', '');
它在您的docs/ api -docs中发布json api描述,例如
localhost:8080/api-docs
当然,您可以将'api-docs‘更改为您想要的任何名称。
要使用swagger-ui检查您的api,您需要将其解压到某个目录中。我的在../swagger-ui/dist中。告诉express以静态的方式为其中的文件提供服务,并为其提供一个路由,如/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界面。要让UI直接显示您的api规格,请在swagger-ui index.html文件中添加您的api-docs url:
window.swaggerUi = new SwaggerUi({
url: "/api-docs",
应该有更好的方法来完成最后的调整,但我还没有发现这一点。
https://stackoverflow.com/questions/29698676
复制相似问题