我正在编写一个后端服务,它向公共API端点发出API请求。来自API的响应以JSON的形式发送。我使用request.js进行API调用,并将实例request.Request返回到任何代码(在本例中,是Express.js中的路由处理程序)。路由处理程序只是将API调用的响应“管道”传递给请求路由的客户端。关于上述情况,我有以下关切:
为了避免混乱讨论,我提供了我正在处理的代码片段(代码没有语法错误,运行也正常):
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
});发布于 2017-08-24 08:02:24
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);中间件/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))https://stackoverflow.com/questions/45855686
复制相似问题