Nodejs 中的中间件流水线

Middleware Pipelining in Nodejs

我正在编写一个向 public API 端点发出 API 请求的后端服务。 API 的响应作为 JSON 发送。我正在使用 request.js 进行 API 调用,并且正在 returning 实例,request.Request 到任何代码(在这种情况下,[=33= 中的路由处理程序) ]).路由处理程序只是 "piping" 从 API 回调到请求路由的客户端的响应。 对于上述情况,我有以下担忧:

  1. 实现 Stream 接口的业务逻辑的最佳方式是什么,我可以直接将 API returned 值传递给中间件函数(基本上,调用return 值上的 pipe 方法,并在将其流式传输到客户端之前传递各种逻辑的中间件)?

  2. 我知道传递给 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
}

App.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
    });

express 鼓励的模式之一是使用中间件作为请求对象的装饰器,在您的情况下,您将通过中间件将 api 连接器添加到请求中,然后再在路线.

app.js

import * as apiConnectorMiddleware from './middleware/api-connector';
import * as getRoute from './routes/get-route'
import * as E from 'express';

 app.use(apiConnectorMiddleware);
 app.get('/myendpoint', getRoute);

middleware/api-connector

import * as request from 'request-promise'
(req, res, next) => {
  req.api = request.get('http://someendpoint.domain.com/public?
  arg1=val1');
  next();
}

routes/get-route

(req, res) => req.api
                 .then(value => res.send(value))
                 .catch(res.status(500).send(error))