typescript - 如何在打字稿中添加扩展功能来表达响应?
问题描述
我想在 Express 中扩展 Response 以包含自定义函数。我想添加一个功能:
sendError(statusCode: number, errorMessage: string)
这样我就可以在任何地方调用它
response.sendError(500, "Unable to process this request at the moment.")
你能告诉我如何实现这一目标吗?我查看了其他一些问题,例如 typescript 中数字的扩展方法,但我仍然有一些疑问:
- 当没有原型时,如何在 Response 上扩展函数?
- 我把扩展函数的定义放在哪里?我可以制作一个包含所有定义的单独文件吗?
- 我是否必须将此函数分配给 Response 的每个对象才能使用它,或者我可以只定义一次并在我项目中任何地方的所有响应对象上使用它?
请帮我解决一下这个。我是 TypeScript 的新手,所以请原谅我在问题中可能犯的任何错误:)
解决方案
Express 对继承自 http 版本的请求和响应对象使用自己的原型。
express
您可以在对象上找到 Express 响应原型,如express.response
.
在普通的 Javascript 中,这将起作用:
const express = require('express');
const app = express();
// add my own method to the response prototype so it can be used
// by any route
express.response.mySend = function(data) {
// this here is the live res object for this particular request
console.log("about to send data with my custom response method");
this.send(data);
}
app.get("/", (req, res) => {
res.mySend("hello");
});
app.listen(80);
要在 TypeScript 中进行这项工作,您需要为express.response
允许您执行此操作的对象进行适当的类型绑定。我不是 TypeScript 人,所以你必须自己承担这部分工作。
仅供参考,请求对象是express.request
并且可以类似地使用。
您也可以像这样在中间件中添加自己的方法,但我认为这会稍微降低效率(如果这很重要的话):
const express = require('express');
const app = express();
// add my own method to the response prototype so it can be used
// by any route
app.use((req, res, next) => {
res.mySend = function(data) {
// this here is the live res object for this particular request
console.log("about to send data with my custom response method");
this.send(data);
});
next();
});
app.get("/", (req, res) => {
res.mySend("hello");
});
app.listen(80);
推荐阅读
- c - 在C中将ASCII字符存储在数组中
- mysql - 通过命令行进行的 Flyway 迁移不起作用
- c - 如何使用 esp_bt_gap_read_rssi_delta 函数从 ESP32 获取蓝牙经典 RSSI?
- angular - Ionic 3项目和base64图像中http帖子中的数据参数
- python - Cefpython cx_freeze 错误
- java - 使用 Java 创建条形图
- spring - spring restservice 异步日志记录功能
- javascript - 如何通过类名获取“this.parent”元素值?
- linux - 如何从文件夹中的脚本文件中运行 100 个 csv 文件(一次一个文件)?
- java-time - Java 11 上的 DateTimeParseException 但适用于 Java 10