1

我正在编写一个向公共 API 端点发出 API 请求的后端服务。API 的响应以 JSON 格式发送。我正在使用 request.js 进行 API 调用,并将实例 request.Request 返回到任何代码(在本例中,是 Express.js 中的路由处理程序)。路由处理程序只是将 API 调用的响应“管道”回请求路由的客户端。我对上述情况有以下担忧:

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

  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
}

应用程序.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
    });
4

1 回答 1

1

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

应用程序.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);

中间件/api 连接器

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

路线/获取路线

(req, res) => req.api
                 .then(value => res.send(value))
                 .catch(res.status(500).send(error))
于 2017-08-24T08:02:24.840 回答