I am writing a backend service that makes API requests to a public API endpoint. The response from the API is sent as a JSON. I am using request.js for making the API calls and, am returning the instance, request.Request to any code (in this case, a route handler in Express.js). The route handler is simply "piping" the response from the API call back to client who, requested the route. I have the following concerns regarding the above scenario:
What's the best way to implement business logic that implements the Stream interface so, I can directly pass the API returned value to the middleware function (basically, invoke pipe method on the return value and, pass the middleware for various logic before streaming it to the client)?
I know that the Express.Response instance passed to every route handler in Express is consumed only once and, must be duplicated if they are to passed as arguments to other functions. Is this approach better in comparison to the method described in (1)?
To avoid cluttering up the discussion, I am providing a snippet of the code that I am working on (the code has no syntax errors, runs properly too):
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
});
One of the pattern encouraged by express is to use the middleware as a decorator of the request object, in your case you would be adding the api connector to the request via a middleware before using it in the route.
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))