我正在编写一个向公共 API 端点发出 API 请求的后端服务。API 的响应以 JSON 格式发送。我正在使用 request.js 进行 API 调用,并将实例 request.Request 返回到任何代码(在本例中,是 Express.js 中的路由处理程序)。路由处理程序只是将 API 调用的响应“管道”回请求路由的客户端。我对上述情况有以下担忧:
实现实现 Stream 接口的业务逻辑的最佳方法是什么,我可以直接将 API 返回值传递给中间件函数(基本上,在返回值上调用管道方法,并在将中间件流式传输到之前传递各种逻辑的中间件)客户)?
我知道传递给 Express 中每个路由处理程序的 Express.Response 实例只使用一次,如果它们要作为参数传递给其他函数,则必须重复。与(1)中描述的方法相比,这种方法是否更好?
为了避免混淆讨论,我提供了我正在处理的代码片段(代码没有语法错误,也可以正常运行):
APIConnector.ts:
import * as Request from 'request';
export class APIConnector{
// All the methods and properties pertaining to API connection
getValueFromEndpoint(): Request.Request{
let uri = 'http://someendpoint.domain.com/public?arg1=val1';
return Request.get(uri);
}
// Rest of the class
}
应用程序.ts
import * as API from './APIConnector';
import * as E from 'express';
const app = E();
const api = new API();
app.route('/myendpoint)
.get((req: E.Request, res: E.Response) => {
api.getValueFromEndpoint().pipe(res);
// before .pipe(res), I want to pipe to my middleware
});