serverless-apigwy-binary
serverless-apigwy-binary copied to clipboard
Works only for custom lambda integration
Please! add a prominent note that this works for custom lambda integration only.
It took me 6 hours to find this.
It seems that it does work with both the Proxy and Custom Lambda setups but there are some changes that need to be made to the output from the Lambdas depending on what configuration you have.
For the Lambda Proxy configuration, the following set up worked for me:
# serverless.yaml
custom:
apigwBinary:
types:
- 'image/jpeg'
functions:
outputBinary:
handler: handler.binary
events:
- http:
path: binary
method: get
contentHandling: CONVERT_TO_BINARY
plugins:
- serverless-apigw-binary
- serverless-apigwy-binary
export const binary = async () => {
const image = readFileSync('cat.jpeg')
const base64 = Buffer.from(image).toString('base64')
return {
statusCode: 200,
headers: { 'Content-type': 'image/jpeg' },
body: base64,
isBase64Encoded: true // Without this it wasn't returning a binary file
}
}
Importantly the you need to set Accept: image/jpeg
on your request to the API Gateway to force the Gateway to convert the binary file and not get a Base64 string
For the Custom Integration configuration, the following set up seems to work:
# serverless.yaml
custom:
apigwBinary:
types:
- 'image/jpeg'
functions:
outputBinary:
handler: handler.binary
events:
- http:
path: binary
method: get
integration: lambda # Switching to lamba setup
contentHandling: CONVERT_TO_BINARY
plugins:
- serverless-apigw-binary
- serverless-apigwy-binary
export const binary = async () => {
const image = readFileSync('cat.jpeg')
const base64 = Buffer.from(image).toString('base64')
// Note below that you don't return an object, return the image/binary directly
// as a Base64 string. Without this you can get the Gateway complaining it can't
// decode the response body from Base64
return base64
}
What's confusing with this setup is that when Lamba Proxy is enabled and you go to the AWS Console, you cannot access there area to configure the binary conversion, so it makes it seem like these values are incompatible, but this value is configurable via the AWS CLI and obviously via the CloudFormation template created by serverless.