Created
June 28, 2018 15:35
-
-
Save ThomasKruegl/d7529fe5cefb718543668eb0bb7dd60b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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