import { IncomingMessage } from 'http' ; import { APIGatewayProxyResult } from 'aws-lambda' ; import { is } from 'type-is' ; import * as binarycase from 'binary-case' ; export class ResponseBuilder { public static buildResponseToApiGateway ( response , resolver , binaryTypes ) { const buf = [ ] ; response . on ( 'data' , ( chunk ) => buf . push ( chunk ) ) . on ( 'end' , ( ) => { const bodyBuffer = Buffer . concat ( buf ) ; const statusCode = response . statusCode ; const headers = response . headers as { [ header ] : string | number | boolean ; } ; if ( headers [ 'transfer-encoding' ] === 'chunked' ) { delete headers [ 'transfer-encoding' ] ; } Object . keys ( headers ) . forEach ( h => { if ( Array . isArray ( h ) ) { if ( h . toLowerCase ( ) === 'set-cookie' ) { h . forEach ( ( value , i ) => { headers [ binarycase ( h , i + 1 ) ] = value ; } ) ; delete headers [ h ] ; } else { headers [ h ] = h . join ( ',' ) ; } } } ) ; const contentType = ResponseBuilder . getContentType ( { contentTypeHeader : headers [ 'content-type' ] , } ) ; let isBase64Encoded = ResponseBuilder . isContentTypeBinaryMimeType ( { contentType , binaryMimeTypes : binaryTypes , } ) ; if ( ! isBase64Encoded ) { isBase64Encoded = headers [ 'content-encoding' ] === 'gzip' ; } const body = bodyBuffer . toString ( isBase64Encoded ? 'base64' : 'utf8' ) ; const successResponse = { statusCode , body , headers , isBase64Encoded , } ; resolver . succeed ( successResponse ) ; } ) ; } public static buildConnectionErrorResponseToApiGateway ( error , resolver ) { console . log ( 'ERROR: aws-serverless-fastify connection error' ) ; console . error ( error ) ; const errorResponse = { statusCode : 502 , body : '' , headers : { } , } ; resolver . succeed ( errorResponse ) ; } public static buildLibraryErrorResponseToApiGateway ( error , resolver ) { console . log ( 'ERROR: aws-serverless-fastify error' ) ; console . error ( error ) ; const errorResponse = { statusCode : 500 , body : '' , headers : { } , } ; resolver . succeed ( errorResponse ) ; } private static getContentType ( params ) { return params . contentTypeHeader ? params . contentTypeHeader . split ( ';' ) [ 0 ] : '' ; } private static isContentTypeBinaryMimeType ( params ) { return ( params . binaryMimeTypes . length > 0 && ! ! is ( params . contentType , params . binaryMimeTypes ) ) ; } }