[英]Using async middleware functions with swagger node project
I have generated an app using swagger-node ( https://github.com/swagger-api/swagger-node ). 我已经使用swagger-node ( https://github.com/swagger-api/swagger-node )生成了一个应用程序。
The automatic swagger router is not recognizing controller middleware functions with an async prefix. 自动swagger路由器无法识别带有异步前缀的控制器中间件功能。 I have to use Promises inside middlewares.
我必须在中间件中使用Promises。
Is there a way to use async in the middlewares which are listed in swagger.yaml ? 在swagger.yaml中列出的中间件中,有没有一种使用异步的方法?
in swagger.yaml: 在swagger.yaml中:
paths:
'/positions/{positionId}':
x-swagger-router-controller: controller
get:
description: some description
operationId: getPosition
in controllers/controller.js 在controllers / controller.js中
module.exports.getPosition = function(request, response) {
const positionId = request.swagger.params.positionId.value;
try {
someModel.getPosition(positionId)
.then(function() {
return response.status(200).json();
})
.catch(function(error) {
return response.status(500).json();
});
} catch(error) {
return response.status(500).json();
}
};
and I would like to write: 我想写:
module.exports.getPosition = async function(request, response) {
const positionId = request.swagger.params.positionId.value;
try {
await someModel.getPosition(positionId);
return response.status(200).json();
} catch(error) {
return response.status(500).json();
}
};
This is an issue of the swagger-node-runner
package (see here ) : 这是
swagger-node-runner
软件包的问题(请参阅此处 ):
they need to they'd need to update their code to use the latest release of
swagger-tools
.他们需要更新代码以使用最新版本的
swagger-tools
。
I fixed that by : 我通过以下方式解决了这个问题:
First, installing the 0.10.3
version of swagger-tools
in the project : 首先,在项目中安装
swagger-tools
的0.10.3
版本:
npm install --save swagger-tools@0.10.3
Then, changing the dependency of swagger-node-runner
manually in the node_modules/swagger-node-runner/package.json
file, like : 然后,在
node_modules/swagger-node-runner/package.json
文件中手动更改swagger-node-runner
的依赖项,例如:
[...]
"dependencies": {
"bagpipes": "^0.0.6",
"config": "^1.16.0",
"cors": "^2.5.3",
"debug": "^2.1.3",
"js-yaml": "^3.3.0",
"lodash": "^3.6.0",
"swagger-tools": "^0.10.3"
},
[...]
For you to use the wait, you are using async in the creation of the function, it follows: 为了使用wait,在函数创建过程中使用了async,它如下:
module.exports.getPosition = async function(request, response) { const positionId = request.swagger.params.positionId.value; try { await someModel.getPosition(positionId); return response.status(200).json(); } catch(error) { return response.status(500).json(); } };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.