2017-08-24 123 views
0

我在寫一個後端服務,它向公共API端點發出API請求。來自API的響應以JSON形式發送。我正在使用request.js進行API調用,並且正在將實例request.Request返回給任何代碼(在本例中爲Express.js中的一個路由處理程序)。路由處理程序簡單地將來自API回調的響應「管道化」回到請求路由的客戶端。 我有一個關於上述情況如下擔憂:Nodejs中的中間件流水線

  1. 什麼是實現一個實現了流接口,這樣的業務邏輯的最好方式,我可以直接通過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 
} 

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

回答

0

一個用快遞鼓勵圖案是使用中間件作爲請求對象的裝飾器,在您的情況下,您將在路由中使用它之前通過中間件將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(); 
} 

路由/ GET-路線

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