如何解决为快递路由器创建装饰器?
为了使代码更加轻量级和可读性,我想出了为 express 路由器创建一个简单的装饰器的想法。
来自:
itemRouter
.get('/:item_id',async (req,res,next) => {
try {
const id = parseInt(req.params.item_id)
const item = await itemController.getItemById(id)
res.status(StatusCodes.OK).send(item)
} catch (error) {
next(error)
}
})
接近这个最终结果:
itemRouter
.get('/:item_id',expressDecorator(async (req,next) => {
const id = parseInt(req.params.item_id)
return itemController.getItemById(id)
})
})
function expressDecorator(wrapped) {
return function () {
const { req,next } = arguments
try {
const { statusCode,bodyResponse } = wrapped.apply(this,arguments)
res.status(statusCode).send(bodyResponse)
} catch (error) {
next(error)
}
}
}
但是我遗漏了一些东西,因为它根本不起作用。它是什么?
PS:我很清楚有一个 express-router-decorator npm 包,但我希望自己做个实验来了解它是如何工作的。
解决方法
您的原始路由器控制器使用 async/await
语法。内部函数也应该使用 async/await
。
例如
const express = require('express');
const app = express();
const port = 3000;
const itemController = {
getItemById(id) {
return { statusCode: 200,bodyResponse: 'test_item_' + id };
},};
app.get(
'/:item_id',expressDecorator(async (req,res,next) => {
const id = parseInt(req.params.item_id);
return itemController.getItemById(id);
}),);
function expressDecorator(wrapped) {
return async function (...args) {
const [req,next] = args;
try {
const { statusCode,bodyResponse } = await wrapped.apply(this,args);
res.status(statusCode).send(bodyResponse);
} catch (error) {
next(error);
}
};
}
app.listen(port,() => console.log(`HTTP server started at http://localhost:${port}`));
通过 curl
测试:
> curl http://localhost:3000/1
StatusCode : 200
StatusDescription : OK
Content : test_item_1
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: timeout=5
Content-Type: text/html; charset=utf-8
Date: Wed,03 Feb 2021 02:32:02 GMT
ETag: W/"b-UjEymk+xUeSCTPOQ7NOHrxuV2as"...
Forms : {}
Headers : {[Connection,keep-alive],[Keep-Alive,timeout=5],[Co
ntent-Length,11],[Content-Type,text/html; charset=ut
f-8]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : System.__ComObject
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。