首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Nodejs中的中间件流水

Nodejs中的中间件流水
EN

Stack Overflow用户
提问于 2017-08-24 07:41:13
回答 1查看 1.4K关注 0票数 1

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

  1. 实现Stream接口的业务逻辑的最佳方法是什么?因此,我可以直接将API返回的值传递给中间件函数(基本上,对返回值调用管道方法,并在流到客户端之前传递各种逻辑的中间件)?
  2. 我知道在Express中传递给每个路由处理程序的Express.Response实例只消耗一次,如果要将它们作为参数传递给其他函数,则必须复制它们。与(1)中描述的方法相比,这种方法更好吗?

为了避免混乱讨论,我提供了我正在处理的代码片段(代码没有语法错误,运行也正常):

APIConnector.ts:

代码语言:javascript
复制
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

代码语言:javascript
复制
 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
    });
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-24 08:02:24

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

app.js

代码语言:javascript
复制
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-连接器

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

路线/获取路线

代码语言:javascript
复制
(req, res) => req.api
                 .then(value => res.send(value))
                 .catch(res.status(500).send(error))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45855686

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档