Skip to content

Instantly share code, notes, and snippets.

@ThomasKruegl
Created June 28, 2018 15:35
Show Gist options
  • Save ThomasKruegl/d7529fe5cefb718543668eb0bb7dd60b to your computer and use it in GitHub Desktop.
Save ThomasKruegl/d7529fe5cefb718543668eb0bb7dd60b to your computer and use it in GitHub Desktop.
export function buildRequestHandler(): RequestHandler {
return (externalRequest: Request, externalResponse: Response, next: NextFunction) => {
const errorHandler = (error: any) => {
if (externalResponse.headersSent) {
return next(error);
}
externalResponse.status(INTERNAL_SERVER_ERROR).json(createDefaultErrorBody(error));
};
const requestCallback: RequestCallback = (error: any, internalResponse: RequestResponse, internalBody: any) => {
if (error) {
errorHandler(error);
} else {
if (isResponseOk(internalResponse.statusCode, internalBody)) {
// cannot pipe anymore, because response was already consumed from stream to read body.
externalResponse.status(internalResponse.statusCode);
externalResponse.header(internalResponse.headers);
externalResponse.send(internalBody);
} else {
const invalidResponseError = new Error("Internal service sent invalid response.");
externalResponse.status(INTERNAL_SERVER_ERROR).json(createDefaultErrorBody(invalidResponseError));
}
}
};
const internalRequest = request(targetUrl, requestCallback);
externalRequest.pipe(internalRequest);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment